Difference between `const shared_ptrlt;Tgt;` and `shared_ptrlt;const Tgt;`?(`const shared_ptrlt;Tgt;`和`shared_ptrlt;const Tgt;`之间的区别?)
问题描述
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;
}
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!
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.
The same holds for weak_ptr
and unique_ptr
.
这篇关于`const shared_ptr<T>`和`shared_ptr<const T>`之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:`const shared_ptr<T>`和`shared_ptr<const T>`之间的区别?


- Qt计时器使用方法详解 2023-05-30
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- C++ 数据结构超详细讲解顺序表 2023-03-25
- C语言qsort()函数的使用方法详解 2023-04-26
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C语言详解float类型在内存中的存储方式 2023-03-27
- Easyx实现扫雷游戏 2023-02-06
- ubuntu下C/C++获取剩余内存 2023-09-18
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30