简体   繁体   English

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

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

I want to have a managed pointer (unique or shared) and be able to reassign it with new piece of memory and also be sure that old memory is deleted (as it's supposed to be) with managed pointers. 我想要一个托管指针(唯一的或共享的),并能够用新的内存重新分配它,并且还要确保使用托管指针删除了旧的内存(应该是这样)。

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

How would I achieve this in most clean way? 我将如何以最干净的方式实现这一目标?

You have several options: 您有几种选择:

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.

相关问题 移动std :: vector <std::unique_ptr<T> &gt;到std :: vector <std::shared_ptr<T> &gt; - Move std::vector<std::unique_ptr<T>> to std::vector<std::shared_ptr<T>> 为什么std :: shared_ptr <T> = std :: unique_ptr <T[]> 编译,而std :: shared_ptr <T[]> = std :: unique_ptr <T[]> 才不是? - Why does std::shared_ptr<T> = std::unique_ptr<T[]> compile, while std::shared_ptr<T[]> = std::unique_ptr<T[]> does not? `std::optional` 相对于 `std::shared_ptr` 和 `std::unique_ptr` 的优势是什么? - What's the advantage of `std::optional` over `std::shared_ptr` and `std::unique_ptr`? const使用std :: unique_ptr / std :: shared_ptr正确合成 - const correct composition using std::unique_ptr / std::shared_ptr 无法将带有NULL删除器的std :: unique_ptr移动到std :: shared_ptr? - Cannot move std::unique_ptr with NULL deleter to std::shared_ptr? std :: unique_ptr和std :: shared_ptr之间的破坏行为差异的基本原理是什么? - What is the rationale for the difference in destruction behavior between std::unique_ptr and std::shared_ptr? 将所有权从std :: shared_ptr移至std :: unique_ptr - Move ownership from std::shared_ptr to std::unique_ptr 如何从 std::shared_ptr 转换为 std::unique_ptr? - How to convert from std::shared_ptr to std::unique_ptr? 如何取得std :: unique_ptr和std :: shared_ptr的所有权 - How to take ownership of std::unique_ptr and std::shared_ptr std :: shared_ptr和std :: unique_ptr构造函数之间的不对称 - assymetry between std::shared_ptr and std::unique_ptr constructors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM