是否有一个与shared_from_this等效的weak_ptr? [英] Is there a weak_ptr equivalent to shared_from_this?
问题描述
我有一个我知道将永远归于std::shared_ptr
的类.但是,将shared_ptr
甚至weak_ptr
传递给不需要所有权或生存期保证的函数和方法会产生不必要的开销.为了解决这个问题,我经常将原始指针传递给函数.类本身是从std::enable_shared_from_this
继承的,因此,如果函数需要获取指针的所有权,则可以使用该类的方法来获取shared_ptr
.
I have a class which I know will always be owned by a std::shared_ptr
. However passing shared_ptr
or even weak_ptr
to functions and methods that don't need ownership or lifetime guarantees creates unnecessary overhead. To get around this I often pass raw pointers to functions. The class itself inherits from std::enable_shared_from_this
so if the function needs to take ownership of the pointer it can use a method of the class to get a shared_ptr
.
一切正常.但是在某些情况下,我并不是真的想从原始指针中创建shared_ptr
,我想要的是weak_ptr
.
This is all working beautifully. However there are occasions where I don't really want to make a shared_ptr
from a raw pointer, what I want instead is a weak_ptr
.
据我对std::shared_ptr
的通常实现的理解,它有两个原子变量用作参考计数器;一个用于shared_ptr
,一个用于weak_ptr
.
From what I understand of the usual implementation of std::shared_ptr
it has two atomic variables used as reference counters; one for shared_ptr
, one for weak_ptr
.
如果我仅有的是指向我班级的原始指针,并且想要一个weak_ptr
,则必须首先创建一个shared_ptr
并将其转换.这样做意味着参考计数器会像这样更改:
If all I have is a raw pointer to my class and I want a weak_ptr
, I must first create a shared_ptr
and convert it. Doing so means the reference counters are altered like this:
- 构造
shared_ptr
,递增shared_ptr
计数器 - 复制构造
weak_ptr
,递增weak_ptr
计数器 - 允许
shared_ptr
超出范围,减小shared_ptr
计数器
- Construct
shared_ptr
, incrementshared_ptr
counter - Copy construct
weak_ptr
, incrementweak_ptr
counter - Allow
shared_ptr
to go out of scope, decrementshared_ptr
counter
这似乎与您不为不使用的商品付费"的想法背道而驰.我的班级有没有办法提供weak_ptr
而不先创建shared_ptr
?
This seems to go against the idea that "you don't pay for what you don't use". Is there a way for my class to just provide weak_ptr
without first creating a shared_ptr
?
推荐答案
我的班级有没有办法在不先创建shared_ptr的情况下仅提供weak_ptr?
Is there a way for my class to just provide weak_ptr without first creating a shared_ptr?
不是在C ++ 14中; enable_shared_from_this
支持的唯一操作是创建shared_ptr
.现在,enable_shared_from_this
应该具有足够的信息来直接构造weak_ptr
.但是您不能从外部进行操作,因为该类不会向您公开其实现细节.
Not in C++14; the only operation that enable_shared_from_this
supports is creating a shared_ptr
. Now, enable_shared_from_this
should have sufficient information to construct a weak_ptr
directly. But you can't do it from the outside, as the class doesn't expose its implementation details to you.
C ++ 17支持通过weak_from_this
从enable_shared_from_this
类中获取weak_ptr
.
C++17 has support for fetching a weak_ptr
from an enable_shared_from_this
class via weak_from_this
.
这篇关于是否有一个与shared_from_this等效的weak_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!