Smart pointers when dealing with constructors

704 views Asked by At

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
2

There are 2 answers

1
ixSci On BEST ANSWER

std::unique_ptr is a wrapper around a pointer so to create a correct object of std::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:

startButton = std::make_unique<Button>(1, "StartButton");

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 using new directly.

0
R Sahu On

If you have a compiler that supports C++14, you can use:

startButton = std::make_unique<Button>(1, "StartButton");

If you are restricted to using C++11, you need to use:

startButton = std::unique_ptr<Button>(new Button(1, "StartButton"));