c++ - Const 与 C++ 中的智能指针

标签 c++ constants smart-pointers copy-constructor

我正在用 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/

相关文章:

c++ - 从一对数组中获取匹配的元素 (C++/OpenCV)

c# - 虽然不可能创建常量属性,但有没有办法在使用常量字段时避免违反 DRY 规则?

c++ - 为什么指向非常量成员函数的指针不能指向与常量成员函数相反的指针?

c++ - 在 shared_ptr 过期后定位 weak_ptr

c++ - 无法使 rustc 使用 simd 指令进行包含范围循环

c++ - Visual Studio 2012 C++ 标准输出

c++ - Thrust中是否有 boost 计算功能的类比?

c++ - 为什么未初始化的 const 成员在 C 中的处理方式与在 C++ 中的处理方式不同?

c++ - 将唯一指针初始化为类成员

c++ - 如何为运算符 ==/!= 编写 C++ 智能指针