一般而言,将T const
转换为T
与const_cast<>
几乎总是不必要的。这是因为常量对象正在转换为非常量临时对象,并且这可以在没有强制转换的情况下安全地完成。
int const n; // n is a constant int
int x = n; // perfectly safe
即使T
是指针类型也是如此。
int * const n; // n is a constant pointer to an int
int * x = n; // perfectly safe
但是,如果移动const
关键字前,它不再是使得指针类型不变,但被指向到常量的类型。因此,我们上面的例子:
const int * n; // n is a pointer to a constant int
int * x = n // error, x is a pointer to an int
你可以看到,x
点,比n
点不同的东西,所以初始化失败。在这种情况下,初始化将需要const_cast<>
:
int * x = const_cast<int *>(n);
// cast away the const-ness that n is pointing to
你只能这样做,如果你知道n
实际上是modifyable(它可能不是如果指针是实际只读存储器),或者如果您知道x
的用户实际上不会尝试修改n
指向的内容。
对于你的榜样,你似乎认为你const
方法应该返回一个指针,以这样一种方式,该数据是由调用者修改你的对象保存数据。也就是说,由于n()
方法被声明为const
,这意味着被访问对象的内容应该被视为常量。因此,n_
是一个常数为int
的数组,它将衰减为指向常量int
的指针,但您要返回指向int
的指针。
如果您打算n_
是可修改的,无论该对象是否被视为常量,您可以使用mutable
声明该意图。这将使n_
被视为非常量,即使包含对象是const
,并且它因此使const_cast
不必要。
class A
{
private:
mutable int n_[10];
public:
/* ... */
int* n() const
{
return n_;
}
};
来源
2015-04-20 19:15:00
jxh
是的,但没有必要。你没有返回一个引用,所以调用者无法通过调用'n()'来修改'n_'。 – jxh
当前的代码试图返回一个'int *'作为'int'。 –
现在你允许我这样做:'const A a; int * p = a.n(); p [0] = 2;'。所以不,它根本就不安全。 – chris