[英]Shared pointers and const correctness
Which is the correct way to extend the const correctness of a class to its pointed members? 将类的const正确性扩展到其尖头成员的正确方法是什么? In the example code, is the constant version of the get method going to create an
std::shared_ptr
whose reference counter is the same as the internal member m_b
, or is it starting again counting from 0
? 在示例代码中,get方法的常量版本是创建
std::shared_ptr
其引用计数器与内部成员m_b
相同,还是从0
开始重新计数?
class A
{
std::shared_ptr< B > m_b;
public:
std::shared_ptr< const B > get_b( ) const
{
return m_b;
}
std::shared_ptr< B > get_b( )
{
return m_b;
}
}
shared_ptr
will always preserve reference counts when you construct from another shared_ptr
; 当您从另一个
shared_ptr
构造时, shared_ptr
将始终保留引用计数; the only way to use it unsafely is to construct from a raw pointer: shared_ptr<...>(my_ptr.get()) // don't do this
. 不安全地使用它的唯一方法是从原始指针构造:
shared_ptr<...>(my_ptr.get()) // don't do this
。
You may also be interested in the propagate_const
wrapper, which is in the Library Fundamentals TS v2 so will probably be available in your implementation quite soon. 您可能还对
propagate_const
包装器感兴趣,该包装器位于Library Fundamentals TS v2中,因此可能很快就会在您的实现中提供。
The answer can be deduced by doing some testing with use_count()
. 通过使用
use_count()
进行一些测试可以推断出答案。
Also notice how method resolution may be not completely obvious: 还要注意方法分辨率可能不是很明显:
class B {};
class A {
std::shared_ptr<B> m_b;
public:
A() { m_b = std::make_shared<B>(); }
std::shared_ptr<const B> get_b() const {
std::cout << "const" << std::endl;
return m_b;
}
std::shared_ptr<B> get_b() {
std::cout << "non const" << std::endl;
return m_b;
}
};
int main(int, char **) {
A a;
std::shared_ptr<B> b = a.get_b();
std::cout << b.use_count() << std::endl;
std::shared_ptr<const B> cb = a.get_b();
std::cout << cb.use_count() << std::endl;
const A &a_const_ref = a;
std::shared_ptr<const B> ccb = a_const_ref.get_b();
std::cout << ccb.use_count() << std::endl;
return 0;
}
Output: 输出:
non const
2
non const
3
const
4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.