3

I am getting error while creating object as shown below using unique_ptr Error: Error conversion from Account * to non-scalar type std::unique_ptr

std::unique_ptr <Account> acc_ptr = new Account(100);

If I use raw pointer as below, there is no error

Account *acc_ptr = new Account(100);

Why is it so?

ligin pc
  • 31
  • 3
  • related (/duplicate?) : https://stackoverflow.com/questions/11367933/why-is-unique-ptrtt-explicit. If the first would compile then also `void foo(std::unique_ptr){} int x; foo(&x);` would compile and that would be bad. – 463035818_is_not_an_ai Jul 05 '21 at 19:01

1 Answers1

6

The std::unique_ptr constructor taking a pointer is explicit.

You need this:

std::unique_ptr <Account> acc_ptr(new Account(100));

Or, since C++14, use the better std::make_unique version:

auto acc_ptr = std::make_unique<Account>(100);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108