使用C++中的智能指针构造Const

luc*_*nte 1 c++ const smart-pointers copy-constructor

我正在用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;
  }
};
Run Code Online (Sandbox Code Playgroud)

这是一种方法,但是我感到不安的是const会员没有返回const指针.另一种可能性是getPointee()返回a const T*const_cast<T*>在复制构造函数中执行a .

有没有更好的方法呢?如果没有,你认为哪个是较小的邪恶,返回一个非常数或做一个const_cast

zen*_*hoy 7

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

int * const int_ptr;
Run Code Online (Sandbox Code Playgroud)

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

Pointer<const int> const_int_smart_ptr;
Run Code Online (Sandbox Code Playgroud)

这基本上相当于:

const int *const_int_ptr;
Run Code Online (Sandbox Code Playgroud)