Skip to content

Forwarding a constructor argument type

Simple construction:

struct SomeStruct
{
    SomeStruct(int in_i, double in_d, const std::string& in_s)
        : i(in_i), d(in_d), s(in_s) {}
    int i;
    double d;
    std::string s;
};

SomeStruct s (4711, 3.14, "Hello");
// => "Hello" is created as string and then copied
//    even when changing to move semantics a move operation would be necessary

Optimizing by forwarding:

struct SomeStructOptimized
{
    template <typename S>
    SomeStructOptimized(int in_i, double in_d, S&& in_s)&
        :
        i(in_i),
        d(in_d),
        s(std::forward<S>(in_s)) //<<< optimization by forwarding
    {}
    int i;
    double d;
    std::string s;
};

SomeStructOptimized sOpt (4711, 3.14, "Hello");
// => string parameter is forwarded into constructor,
//    string is constructed only once, directly within struct fooOptimized