Omrum Cetin
Omrum Cetin

Reputation: 1479

Function Params as 'const T&' and 'T&&'

Need to understand and figure out how to work efficiently with these 2 definitions on lowlevel.

void func(const T& foo)
{
    T bar = foo;
}

// Lets overload this
void func(T&& foo)
{
    T bar = foo;
}

Here is what I know already.

So what is the fundemental reason, whats the main get of differenciates usage? I'm not expecting const T& also doesnt create copy for passed param as well. Or is it ? So went to oblivion, need clear answer on this.

Edit : I guess need to do addition. Asked question as int but this is mainly valid for any class type which we are going to avoid copies.

Edit : Converting question on generic typename T, to be more certain on questions intentions.

Upvotes: 0

Views: 139

Answers (2)

Fareanor
Fareanor

Reputation: 6805

"So what is the fundemental reason, whats the main get of differenciates usage?"

If both of your overload do exactly the same thing, there is no point of having the rvalue-qualified one since a T && can be bound to a const T & (and you're already aware of that).

The need to have the rvalue overload is when you need to do something different if an rvalue is passed (for example, move-assign the object into another one or anything else you could think of).

"I'm not expecting const int& also doesnt create copy for passed param as well. Or is it ?"

A reference, no matter how qualified, is still a reference. So whether you accept your argument through a const T & or a T &&, no copy is made.

Upvotes: 2

Miles Budnek
Miles Budnek

Reputation: 30639

Rvalue references exist to enable move semantics. For efficiently-copyable types like int there is generally no reason to explicitly use an rvalue reference (copying and moving an int do the same thing).

Rvalue references are needed to enable move semantics because:

  1. You can't tell if a reference-to-const is an rvalue or lvalue
  2. You can't modify the object referenced by a reference-to-const to steal the resources it owns

So, as a general rule: use rvalue references when you want to move from an object passed by reference, and use lvalue references-to-const when you don't.

Upvotes: 2

Related Questions