vendredi 26 mars 2021

How do you initialise a std::unique_ptr to a reference

With raw pointers I can do:

int x = 10;
int* y = &x;

x = 20;
std::cout << *y; //prints 20

However, Im struggling to emulate the same behaviour with std::unique_ptr. Ive tried:

int x = 10;

std::unique_ptr<int> y = std::make_unique(&x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int>(&x); //doesnt compile
std::unique_ptr<int&> y = std::make_unique(x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int&>(&x); //doesnt compile

std::unique_ptr<int> y = std::make_unique<int>(x); //compiles but prints y = 10, which is not the desired behaviour

Im sure there is a way, so any help is appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire