0

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
Daqs
  • 720
  • 3
  • 8
  • 28

2 Answers2

4

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.

ixSci
  • 13,100
  • 5
  • 45
  • 79
  • 1
    The missing of `make_unique` in C++11 was a simple oversight by the committee, but you can simply build your own implementation of `make_unique` in C++11, as pointed out in [this](http://stackoverflow.com/a/12580468/1070117) answer. – Leandros Jun 05 '15 at 08:08
1

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"));
R Sahu
  • 204,454
  • 14
  • 159
  • 270