2

Say I have an initialised object Foo_obj of a class Foo and wish to create a unique smart pointer to a copy of this object. The code auto pointer = make_unique<Foo>(Foo_obj) executes and does exactly this. However when looking at the reference for std::make_unique, this only accepts R-value references as arguments and calls the constructor of the respective class with these arguments.

My understanding is that an object such as Foo_obj is an l-value and thus the above code should not compile. What am I missing?

Jon
  • 47
  • 1
  • 7

1 Answers1

2

When you have something like template <typename T> void foo (T&& rt) {...} something called reference collapsing happens and that's what Meyers calls "A universal reference". In a nutshell, if you pass an rvalue, this becomes an rvalue reference, if you pass an lvalue, this becomes an lvalue reference. This way, the function perfectly forwards all the parameters to the constructor of the unique_ptr.

Learn more about the universal references in this blog post by the man himself.

Quentin
  • 62,093
  • 7
  • 131
  • 191
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93