簡體   English   中英

重新創建(重新分配)std :: shared_ptr或std :: unique_ptr

[英]recreate(reassign) a std::shared_ptr or std::unique_ptr

我想要一個托管指針(唯一的或共享的),並能夠用新的內存重新分配它,並且還要確保使用托管指針刪除了舊的內存(應該是這樣)。

struct MyStruct
{
       MyStruct(signed int) { }
       MyStruct(unsigned float) { }
};
std::unique_ptr<MyStruct> y(new MyStruct(-4)); // int instance
std::shared_ptr<MyStruct> x(new MyStruct(-5));

// do something with x or y
//...


// until now pointers worked as "int" next we want to change it to work as float

x = new MyStruct(4.443);
y = new MyStruct(3.22); // does not work

我將如何以最干凈的方式實現這一目標?

您有幾種選擇:

x = std::unique_ptr<MyStruct>(new MyStruct(4.443));
x = std::make_unique<MyStruct>(4.443); // C++14
x.reset(new MyStruct(4.443));

y = std::shared_ptr<MyStruct>(new MyStruct(3.22));
y = std::make_shared<MyStruct>(3.22);
y.reset(new MyStruct(3.22));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM