我正在用 C++ 编写一个智能指针实现,但我在常量正确性方面遇到了一些麻烦。以下是代码的摘录:
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
感到不安成员(member)未返回 const
指针。另一种可能性是让 getPointee()
返回 const T*
并执行 const_cast<T*>
在复制构造函数中。
有更好的方法吗?如果不是,你认为哪个是较小的邪恶,返回一个非常量或做一个 const_cast
?
最佳答案
最好将常量智能指针视为指向非常量对象的常量指针。这类似于:
int * const int_ptr;
如果你想要一个指向常量对象的指针:
Pointer<const int> const_int_smart_ptr;
基本上等同于:
const int *const_int_ptr;
关于c++ - Const 与 C++ 中的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7905773/