Angelus Mortis
Angelus Mortis

Reputation: 1554

Comparison between usage of std::forward

Consider the simple code (Disclaimer: This is a noobie question) :

template<typename T> struct foo
{
foo(const T&);
foo(T&& ctorArguement):ptrToSomeType(new someType(std::forward<T&&>(ctorArguement))){}
                                                                ^^
std::unique_ptr<someType> ptrToSomeType;
}

compared to this :

template<typename T> struct foo
{
foo(const T&);
foo(T&& ctorArguement):ptrToSomeType(new someType(std::forward<T>(ctorArguement))){}
                                                               ^^
std::unique_ptr<someType> ptrToSomeType;
}

I think I should have used std::move but I was wondering particularly about these two cases. So are two version completely equal, or one is better than another?.

Upvotes: 1

Views: 113

Answers (1)

Brian Bi
Brian Bi

Reputation: 119089

Those two code snippets do the same thing. The first one casts to T&& &&, which is T&&. The second one casts to T&&. Using std::move would have the same effect.

To avoid confusing readers of the code (this includes yourself), you should use std::move in this context. std::forward<T> is only supposed to be used when the T is deduced from a forwarding reference T&&, and that's not the case in your code since the T is actually a parameter for the enclosing class, not the function. As for std::forward<T&&>, it does the same thing as std::forward<T> when the latter is applicable, but this is not at all obvious, so it will also confuse readers.

Upvotes: 7

Related Questions