【发布时间】:2015-12-20 12:26:57
【问题描述】:
给定一个代码(真正的伪代码):
struct A { /* ... */ }; // assume is non-trivial
struct B { /* ... */ }; // assume is non-trivial
using UA = std::unique_ptr< A >;
using UB = std::unique_ptr< B >;
union U
{
UA a;
UB b;
};
U u{std::make_unique< A >(/* init */)};
u.a = nullptr; // destructor of underlying type A called
// u.a.~UA(); // destructor of smart pointer itself
::new (&U.b) UB{std::make_unique< B >(/* init */)};
是否可以省略U::a 成员的析构函数调用?这个问题的灵感来自于关注quote 关于std::unique_ptr::~unique_ptr:
如果 get() == nullptr 没有效果。
我可以认为这种情况下的 d-tor 是微不足道的(如下所述)吗?
我认为std::unique_ptr< T > 的内部(在std::unique_ptr 没有自定义删除器的情况下是唯一的)数据成员(比如p)是T * 类型。在分配p = nullptr; 之后,似乎可以对这样的std::unique_ptr 不做任何事情,以便将其存储用于其他目的。是正确的结论吗?
【问题讨论】:
-
@deviantfan 这只是一个优化。在代码的现实生活部分(堆变体类)中,我应该交换两个类似
U的结构。该代码中没有放置::new,因此不应显式调用析构函数(只是成语)。
标签: c++ destructor c++14 smart-pointers unique-ptr