gpt4 book ai didi

c++ - 使用 shared_ptr : C++ 管理多个对象

转载 作者:行者123 更新时间:2023-11-30 00:49:16 27 4
gpt4 key购买 nike

我正在尝试编写 Manager class,它将管理 Test Class 的多个实例。我应该能够通过调用 mng.drop(指向要删除的实例的共享指针) 来销毁 Test Class 的实例。

我不应该使用 unique_ptr 如何使用 shared_ptr 实现

#include <iostream>
#include <iomanip>
#include <memory>
#include <set>

#define DEBUG ON

#ifdef DEBUG
#define DEBUG_MSG(str) do {std::cout << std::setw(75) << std::left << __FUNCTION__ \
<< std::setw(3) << std::left << ":" << std::setw(5) << std::left << __LINE__ \
<< std::setw(5) << std::left << ":"\
<< std::left << str \
<< std::endl;} while( false )
#else
#define DEBUG_MSG(str) do { } while ( false )
#endif


class Test{
public:
Test(int i) : i_(i){
DEBUG_MSG("Constructor");
}
~Test(){
DEBUG_MSG("Destructor");
}
int getI() { return i_; }
void setI(int i){ i_ = i; }
void fn()
{
DEBUG_MSG("Do Something Here");
}
private:
int i_;
};

using sharedPtr = std::shared_ptr < Test >;


class Manager{
public:
sharedPtr createTest(int i)
{
auto ptr = std::make_shared<Test>(i);
list_.insert(ptr);
return ptr;
}

void drop(sharedPtr ptr)
{
list_.erase(ptr);
}

private:
std::set<sharedPtr> list_;
};

int main()
{
Manager mng;
auto test = mng.createTest(50);
DEBUG_MSG("test : " << test.use_count());
test->fn();
mng.drop(test);
DEBUG_MSG("test : " << test.use_count());

system("Pause");
return 0;
}

可以看出:在我的代码中,当我调用 mng.drop(test) - 仍然引用计数为 1,因此对象没有被销毁。

Test::Test                                                                 :  22   :    Constructor
main : 62 : test : 2
Test::fn : 31 : Do Something Here
main : 65 : test : 1
Press any key to continue . . .

编辑

My requirement: Manager Class should hold shared_ptr to all Test instances active; It should able to create and destroy Test instance

最佳答案

createTest 返回并存储在test 中的指针与管理器管理的指针共享所有权;在两者都被删除之前,该对象不会被销毁。

createTest 应该返回 weak_ptr如果它的客户应该在不共享所有权的情况下访问对象。他们可以临时锁定指针以防止在需要访问时被删除;尽管您必须相信他们不会永久锁定它,但如果出于某种原因对经理来说拥有这种“独特”的所有权真的很重要的话。

关于c++ - 使用 shared_ptr : C++ 管理多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28602370/

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