c++中带有智能指针的Const

Const with smart pointers in C++

本文关键字:指针 Const 智能 c++      更新时间:2023-10-16

我正在用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成员不返回const指针感到不安。另一种可能是让getPointee()返回一个const T*,并在复制构造函数中执行一个const_cast<T*>

有更好的方法吗?如果不是,您认为返回非const和执行const_cast,哪个害处较小?

最好将常量智能指针视为指向非常量对象的常量指针。这类似于:

int * const int_ptr;

如果你想要一个指向常量对象的指针:

Pointer<const int> const_int_smart_ptr;

基本上相当于:

const int *const_int_ptr;

pointee指定的对象似乎不属于Pointer,所以我认为没有理由假设调用const函数Pointer将返回T const*,而不是T*。(如果指向的对象在概念上是Pointer的一部分,当然问题就不一样了