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

cod*_*ddy 2 c++ shared-ptr 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
Run Code Online (Sandbox Code Playgroud)

我怎样才能以最干净的方式实现这一目标?

Dan*_*rey 6

你有几个选择:

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));
Run Code Online (Sandbox Code Playgroud)