【发布时间】:2020-05-06 01:28:32
【问题描述】:
有人能解释一下为什么类bar的析构函数在同类型对象被初始化的那一行被调用吗?
#include <memory>
#include <iostream>
using namespace std;
class bar
{
public:
bar() {}
~bar() { std::cout << "destructor called " << std::endl; }
};
class foo
{
public:
foo(std::shared_ptr<bar> barP) {}
};
int main() {
std::shared_ptr<foo> f;
std::cout << "before init " << std::endl;
f = std::shared_ptr<foo>(new foo(std::shared_ptr<bar>(new bar())));
std::cout << "after init" << std::endl;
}
输出:
before init
destructor called
after init
【问题讨论】:
-
foo 的构造函数获得了
barP的所有权,但不对其做任何事情。在f=...行结束后,您希望哪个shared_ptr<>在bar上保持引用计数?
标签: c++ c++11 shared-ptr smart-pointers