Difference between `const shared_ptrlt;Tgt;` and `shared_ptrlt;const Tgt;`?(`const shared_ptrT`和`shared_ptrconst T`之间的区别?)
问题描述
我正在为 C++ 中的共享指针编写一个访问器方法,它是这样的:
I'm writing an accessor method for a shared pointer in C++ that goes something like this:
class Foo {
public:
return_type getBar() const {
return m_bar;
}
private:
boost::shared_ptr<Bar> m_bar;
}
所以为了支持 getBar() 的常量性,返回类型应该是一个 boost::shared_ptr 以防止修改 Bar> 它指向.我的猜测是 shared_ptr 是我想要返回的类型,而 const shared_ptr 会阻止重新分配指针本身指向不同的 Bar 但允许修改它指向的 Bar... 但是,我不确定.如果知道的人可以确认这一点,或者如果我弄错了,我将不胜感激.谢谢!
So to support the const-ness of getBar() the return type should be a boost::shared_ptr that prevents modification of the Bar it points to. My guess is that shared_ptr<const Bar> is the type I want to return to do that, whereas const shared_ptr<Bar> would prevent reassignment of the pointer itself to point to a different Bar but allow modification of the Bar that it points to... However, I'm not sure. I'd appreciate it if someone who knows for sure could either confirm this, or correct me if I got it wrong. Thanks!
推荐答案
你说得对.shared_ptr 类似于const T * p;(或等价于T const * p;),即指向的对象是const 而 const shared_ptr 与 T* const p; 类似,这意味着 p 是 const.总结:
You are right. shared_ptr<const T> p; is similar to const T * p; (or, equivalently, T const * p;), that is, the pointed object is const whereas const shared_ptr<T> p; is similar to T* const p; which means that p is const. In summary:
shared_ptr<T> p; ---> T * p; : nothing is const
const shared_ptr<T> p; ---> T * const p; : p is const
shared_ptr<const T> p; ---> const T * p; <=> T const * p; : *p is const
const shared_ptr<const T> p; ---> const T * const p; <=> T const * const p; : p and *p are const.
同样适用于 weak_ptr 和 unique_ptr.
这篇关于`const shared_ptr<T>`和`shared_ptr<const T>`之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:`const shared_ptr<T>`和`shared_ptr<const T>`之间的区别?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
