shared_ptr从unique_ptr到数组 [英] shared_ptr from unique_ptr to an array
问题描述
Scott Meyers在他的书Effective Modern C ++中提到,使用 shared_ptr
到数组是不鼓励的,因为当转换为Base类指针时,它创建
Scott Meyers mentions in his book, Effective Modern C++, that using shared_ptr
to arrays is discouraged because when converted to Base class pointers it creates "holes" in the type system.
但是,可以从<$ c $>创建 shared_ptr< T>
c $ c> unique_ptr< T []> 。
However, it is possible to create shared_ptr<T>
from unique_ptr<T[]>
in the following way
std::shared_ptr<D> pDerived = std::shared_ptr<D>(std::make_unique<D[]>(3)); // Create an array of 3 D's
上述代码有潜在的危险吗?如果 pDerived
以后被复制到 pBase
?
Is the above code potentially dangerous? Are there pitfalls if pDerived
is later copied into a pBase
?
std::shared_ptr<B> pBase = pDerived; // B is the base class for D
推荐答案
上述代码有潜在的危险吗?
Is the above code potentially dangerous?
这取决于你做什么。
它不会泄露资源,因为使用 delete [] $的
default_delete
unique_ptr
中复制并存储在 shared_ptr
中(如从unique_ptr< T []> 初始化shared_ptr< T> )。
It won't leak resources because the default_delete<D[]>
that uses delete[]
will be copied from the unique_ptr
and stored in the shared_ptr
(as described at Initialization of shared_ptr<T> from unique_ptr<T[]>).
如果
pDerived
稍后复制到pBase
?
是的,如果你执行 pBase.get()[1]
指向第二个元素的有效指针if sizeof(B)!= sizeof(D)
Yes, if you do something like pBase.get()[1]
then that is not a valid pointer to the second element if sizeof(B) != sizeof(D)
std :: experimental :: shared_ptr
从 Library Fundamentals TS 正确地支持数组(由
std::experimental::shared_ptr
from the Library Fundamentals TS supports arrays properly (as proposed by N3939).
使用TS中的版本, shared_ptr< D>
不允许从 unique_ptr
,但 shared_ptr< D []>
。不能将 shared_ptr< D []>
转换为 shared_ptr< B []>
With the version in the TS, shared_ptr<D>
does not allow construction from a unique_ptr<D[]>
, but shared_ptr<D[]>
does. A shared_ptr<D[]>
cannot be converted to shared_ptr<B[]>
, to avoid the safety problem you refer to.
对于数组的支持可能会在未来的C ++标准中变成 std :: shared_ptr
,但是现在只在TS中。
The support for arrays might make it into std::shared_ptr
in a future C++ standard, but is only in the TS for now.
这篇关于shared_ptr从unique_ptr到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!