gpt4 book ai didi

c++ - 你如何通过传递 "this"关键字来分配 weak_ptr?

转载 作者:行者123 更新时间:2023-11-30 01:02:12 26 4
gpt4 key购买 nike

在我的程序中,Groups 将共享指向 Subjects 的指针;并且 Subjects 将有指向其 Groups 的弱指针。我希望 Group 有一个 join() 函数,将 Subject 的弱指针分配给它自己。以下是我尝试过的最少代码。如何修复 join() 函数?

#include <iostream>
#include <string>
#include <memory>

class Party;

class Subject
{
public:
std::weak_ptr<Party> MyParty;
};

class Party
{
public:
std::string Name;

void join(std::shared_ptr<Subject> subject)
{
subject->MyParty = std::make_shared<Party>(*this); // <---- PROBLEM
}
};

int main()
{
auto& BlueParty = std::make_shared<Party>();
BlueParty->Name = "Blue Party";

auto& Jane = std::make_shared<Subject>();

BlueParty->join(Jane);

if (auto ptr = Jane->MyParty.lock())
{
std::cout << "I am in " << ptr->Name << std::endl;
}

else { std::cout << "I have no party." << std::endl; }

return 0;
}

程序打印出“I have no party”。如果赋值成功,应该会打印出“I am in Blue Party”。

最佳答案

subject->MyParty = std::make_shared<Party>(*this);创建一个新的 Party作为 *this 拷贝的对象并由临时 std::shared_ptr 管理. subject->MyParty从临时 shared_ptr 分配,但是weak_ptr不要让它们指向的对象保持事件状态。一旦该语句完成,临时 shared_ptrmake_shared 返回被销毁并获得 Party它正在管理的对象。 subject->MyParty now 没有指向任何东西。

解决方案是使用 std::enable_shared_from_this :

class Party : public std::enable_shared_from_this<Party>
{
public:
std::string Name;

void join(std::shared_ptr<Subject> subject)
{
subject->MyParty = shared_from_this();
}
};

Example

使用shared_from_this , 该对象必须 属于 std::shared_ptr .在这种情况下,将类的构造函数标记为 private 通常是个好主意。并使用返回 shared_ptr 的工厂函数到一个新实例,以便该类型的对象不受 shared_ptr 管理不能意外创建:

class Party : public std::enable_shared_from_this<Party>
{
public:
std::string Name;

static std::shared_ptr<Party> create()
{
return std::shared_ptr<Party>{new Party()};
}

void join(std::shared_ptr<Subject> subject)
{
subject->MyParty = shared_from_this();
}
private:
Party() = default;
Party(const Party&) = delete;
};

Example

可悲的是,这使得 std::make_shared更难使用。有关该问题的更多信息,请参阅 this question .

关于c++ - 你如何通过传递 "this"关键字来分配 weak_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56599473/

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