Factory functions

suggest change

Suppose we want to write a factory function that accepts an arbitrary list of arguments and passes those arguments unmodified to another function. An example of such a function is make_unique, which is used to safely construct a new instance of T and return a unique_ptr<T> that owns the instance.

The language rules regarding variadic templates and rvalue references allow us to write such a function. This implementation is the C++11 pattern; std::make_unique itself was added in C++14.

template<class T, class... A>
std::unique_ptr<T> make_unique(A&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<A>(args)...));
}

The ellipsis ... indicates a parameter pack, which represents an arbitrary number of types. The compiler will expand this parameter pack to the correct number of arguments at the call site. These arguments are then passed to T’s constructor using std::forward. That function preserves the value category of each argument.

struct foo
{
    foo() {}
    foo(const foo&) {}                    // copy constructor
    foo(foo&&) {}                         // move constructor
    foo(int, int, int) {}
};

foo f;
auto p1 = make_unique<foo>(f);            // calls foo::foo(const foo&)
auto p2 = make_unique<foo>(std::move(f)); // calls foo::foo(foo&&)
auto p3 = make_unique<foo>(1, 2, 3);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents