2

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?

1
  • 1
    There's no such thing as an unsigned float, just float works. You should also use new MyStruct(4.443f) to avoid an ambiguous call issue since 4.443 is a double and can be converted to either an int or float. Commented Jul 26, 2014 at 7:37

1 Answer 1

6

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.