如果对象被声明为 const,我想中断编译。
以下不起作用:
#include <type_traits>
struct A {
A() : v(0)
{
static_assert( ! std::is_const<decltype(*this)>::value, "declared as const" );
}
int& AccessValue() const
{
return const_cast< int& >( v );
}
int v;
};
int main()
{
A a1; // ok, this compiles
const A a2; // no, this break the compilation
a1.AccessValue() = 5; // ok
a2.AccessValue() = 6; // OPS
}
那么,如果这种类型的对象被声明为 const,有没有办法打破编译呢?
你走错方向了。
的类型this
纯粹由您使用它的方法的签名决定。那是,this
总是类型cv T* const
where cv
对应于方法的 CV 限定符。
因此,在构造函数中,this
只是T* const
.
const_cast
是一种代码味道,通常仅在处理时使用const
-损坏的遗留库...或者(有时)以避免违反 DRY。在新代码中,您不必使用它。
你有一个选择:
- make
AccessValue
非常量,因为它不是
- declare
i
作为存在mutable
.
我建议选择前一种解决方案。放弃一个句柄private
属性已经不好了(破坏了封装),不需要违反const
正确性也是如此。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)