gpt4 book ai didi

C++ make_shared 两次调用析构函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:27:21 26 4
gpt4 key购买 nike

<分区>

我有一些代码让我感到困惑。我一直在学习 shared_pointers 并且正在关注 youtube 上的指南。我正在使用 make_shared 构建我的 Dog,并将共享指针分配给 p。

class Dog
{
private:
std::string name;
public:
Dog(std::string _name):
name(_name)
{
std::cout << "Creating dog with name " << name << std::endl;
}

~Dog() { std::cout << "Destroying dog!" << std::endl; }

void bark()
{
std::cout << name << " barks like a Dog! Woof!" << std::endl;
}
};

std::shared_ptr<Dog> foo()
{
std::cout << "Entering foo" << std::endl;
std::shared_ptr<Dog> p = std::make_shared<Dog>("Tank"); //will be deleted when freed off stack

std::cout << "Dog use count = " << p.use_count() << std::endl;

std::shared_ptr<Dog> p2 = p;

std::cout << "Dog use count = " << p.use_count() << std::endl;

std::cout << "Returning first pointer from foo!" << std::endl;
return p;
}
int main()
{
std::shared_ptr<Dog> p = foo();

std::cout << "Dog use count = " << p.use_count() << std::endl;

return 0;
}

编译为

g++ shared_ptr.cpp

但是,这是我的输出:

Entering foo
Creating dog with name Tank
Destroying dog!
Destroying dog!
Dog use count = 1
Dog use count = 2
Returning first pointer from foo!

谁能解释一下构造然后以某种方式双重破坏的逻辑?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com