Reousa Asteron
Reousa Asteron

Reputation: 529

Does return use move or copy semantics by default?

Moving from C# to C++, trying to understand what happens under the hood.

Given:

int ReturnSomething(){
    int i = 1;
    return i;
}

Is move prioritized over copy in C++17? If so, would the same rules apply for user-defined types, where move constructors are explicitly defined?

Upvotes: 3

Views: 126

Answers (1)

eerorika
eerorika

Reputation: 238321

Does return use move or copy semantics by default?

Depends.

Is move prioritized over copy in C++17?

The exact rules are a bit complicated, but in general, if move is possible then it is preferred over copy.

In some cases, there isn't even a move. For example:

T ReturnSomething(){
    return 1;
}
T t = ReturnSomething();

There is no copying involved. An object is allocated for the t variable, and ReturnSomething initialises that object directly. There is no temporary object involved.

Of course, there is no observable difference when the type is trivially movable / copyable like int is. Even if there was a copy, it could be optimised away. And there is no difference between copying and moving an integer.

Upvotes: 5

Related Questions