[英]Shared pointers and const correctness
將類的const正確性擴展到其尖頭成員的正確方法是什么? 在示例代碼中,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
構造時, shared_ptr
將始終保留引用計數; 不安全地使用它的唯一方法是從原始指針構造: shared_ptr<...>(my_ptr.get()) // don't do this
。
您可能還對propagate_const
包裝器感興趣,該包裝器位於Library Fundamentals TS v2中,因此可能很快就會在您的實現中提供。
通過使用use_count()
進行一些測試可以推斷出答案。
還要注意方法分辨率可能不是很明顯:
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;
}
輸出:
non const
2
non const
3
const
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.