Perfect Forwarding Forwards Objects Not Braced Things Trying To Become Objects -- Raymond Chen

RaymondChen_5in-150x150.jpgIn C++, perfect forwarding is the act of passing a function’s parameters to another function while preserving its reference category. It is commonly used by wrapper methods that want to pass their parameters through to another function, often a constructor.

Perfect Forwarding Forwards Objects, Not Braced Things That Are Trying To Become Objects

By Raymond Chen

From the article:

In C++, perfect forwarding is the act of passing a function’s parameters to another function while preserving its reference category. It is commonly used by wrapper methods that want to pass their parameters through to another function, often a constructor.

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

The make_unique function takes its parameters, forwards them to the T constructor, and then puts the pointer to the newly-constructed T inside a unique_ptr. Those parameters are forwarded perfectly into the constructor: If the original parameters were rvalue reference, then the constructor receives rvalue reference. If the original parameters were lvalue references, then the constructor receives lvalue reference.

But the catch is that it can forward only objects. It can’t forward “braced things that are trying to become objects”.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.