Reputation: 34396
Imagine I have const Matrix IDENTITY_MATRIX
defined somewhere, ready to be copied whenever I need it as a baseline. Matrix
is just a struct
.
If I want to create a smart pointer to a new Matrix
instance, initialized with a copy of IDENTITY_MATRIX
, I could do this:
std::unique_ptr<Matrix> foo(new Matrix);
*foo = IDENTITY_MATRIX;
Is there a way to perform the initialization using a single statement? I don't want to have to write a helper function to do this. If that is required, I'll settle for initialization with two statements.
Upvotes: 1
Views: 5329
Reputation: 60969
Use the new
expression to provide an initializer
std::unique_ptr<Matrix> foo(new Matrix(IDENTITY_MATRIX));
Or use make_unique
auto foo = std::make_unique<Matrix>(IDENTITY_MATRIX);
Upvotes: 3