c++中带有智能指针的Const
Const with smart pointers in C++
我正在用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
的一部分,当然问题就不一样了
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 使用共享指针的函数调用,其对象应为 const
- 为什么通过指针编译时不能分配 const 初始化
- 如果我在 const 函数上使用指针,我可以返回什么?
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- 为什么指针没有隐式转换为 <type> const*const
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- 为什么我可以更改指针的常数(const char *)槽的值
- 错误:"->"的基本操作数具有非指针类型"const"
- 无法将参数 3 从 'const QGraphicsItem *' 转换为 'const QObject *',这是指针,对象是 QGraphicsObject 的子类
- 为什么 map::找不到指向 const 的指针?
- std :: allocator_traits ::用const指针构造
- 如何为const char double指针(使用新的)动态分配内存
- 功能指针参数参数转换为const
- 了解const自动指针
- 从 'void *' 转换为 'const std::string *&' 必须具有所有中间指针 const 合格
- visual studio 2013 - x86/ c++ -指针指向指针:Const被编译器违反