[
Example 3:
template<class T, class A1>
shared_ptr<T> factory(A1&& a1) {
return shared_ptr<T>(new T(std::forward<A1>(a1)));
}
struct A {
A();
A(const A&);
A(A&&);
};
void g() {
A a;
shared_ptr<A> sp1 = factory<A>(a);
shared_ptr<A> sp2 = factory<A>(std::move(a));
}
In the first call to
factory,
A1 is deduced as
A&, so
a is forwarded
as a non-const lvalue
. This binds to the constructor
A(const A&),
which copies the value from
a. In the second call to
factory, because of the call
std::move(a),
A1 is deduced as
A, so
a is forwarded
as an rvalue
. This binds to the constructor
A(A&&),
which moves the value from
a. —
end example]