我正在用C ++编写一个智能指针实现,而且我在使用const-correctness方面遇到了一些麻烦。以下是代码的摘录:
template <class T> class Pointer {
T* pointee;
public:
Pointer(const Pointer<T>& other) { // must be const Pointer& for assignments
pointee = other.getPointee();
}
T* getPointee() const {
return pointee;
}
};
这是一种方法,但我感到不安const
成员没有返回const
指针。另一种可能性是让getPointee()
返回const T*
并在复制构造函数中执行const_cast<T*>
。
有更好的方法吗?如果没有,你认为哪个是较小的邪恶,返回非常数或做const_cast
?
答案 0 :(得分:7)
最好将常量智能指针视为指向非常量对象的常量指针。这类似于:
int * const int_ptr;
如果你想要一个指向常量对象的指针:
Pointer<const int> const_int_smart_ptr;
基本上相当于:
const int *const_int_ptr;
答案 1 :(得分:4)
pointee
指定的对象似乎不属于Pointer
,
所以我认为没有理由假设调用const
函数
Pointer
会返回T const*
,而不是T*
。 (如果
当然,指向对象在概念上是Pointer
的一部分
问题会有所不同。)