This question is in regards to my program. I was earlier using Manual Management using pointers, and now I'm trying to move to smart pointers (for all the good reasons).
In normal pointers, it was easy to call a constructor of a class by using the new keyword. Like in the program below:
Button * startButton;
startButton = new Button(int buttonID, std::string buttonName);
When using smart pointers, what's the alternate way of calling a constructor for a class. What I've done below gives an error:
std::unique_ptr<Button> startButton;
startButton = std::unique_ptr<Button>(1, "StartButton"); // Error
The error I get is as follows:
Error 2 error C2661: 'std::unique_ptr<Button,std::default_delete<_Ty>>::unique_ptr' : no overloaded function takes 2 arguments
std::unique_ptr
is a wrapper around a pointer so to create a correct object ofstd::unique_ptr
you should pass a pointer to its constructor:startButton = std::unique_ptr<Button>(new Button(1, "StartButton"));
Since C++14 there is also a helper function
make_unique
which does this allocation for you under the hood:Prefer to use
std::make_unique
if it is available since it is easier to read and in some cases using it is safer than usingnew
directly.