C++11 tuple with copy elision or move semantic

727 views Asked by At

I wrote a function like below:

template <typename T>
std::tuple<std::vector<T>, T, T> f() {
    std::vector<T> p(1000);
    return std::make_tuple(std::move(p), 10, 10);
}

Since the return type is quite complicated, is it guaranteed that under c++11 the compiler will either apply copy elision or move semantic when it constructs the result or I have to explicitly say something like std::move(std::make_tuple(std::move(p), 10, 10))?

1

There are 1 answers

0
luk32 On

AFAIK copy elision is always optional. Standard just explicitly say that compiler is allowed to make such optimization, because it changes the observable behaviour, it does not mandate it. Specifically 12.8 p. 31:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects.

Disclaimer: This is from community draft n3690, but version for c++11 has similar statement if not exactly the same.

By the way, the criteria are specified right there.

For move, however, it is guaranteed. You make a temporary object and return it (i.e. std::make_tuple returns an rvalue and you pass it forward), the arguments to the template do not change the support for move semantics.