Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 - tuple and move semantics

Tags:

c++

c++11

Should this sample code compile? clang and g++ accept it, while icc 14 refuses to do so, complaining on auto t = ... that the std::unique_ptr's copy constructor is undefined.

#include <iostream>
#include <memory>
#include <tuple>

std::tuple<std::unique_ptr<int[]>, int> foo()
{
    std::unique_ptr<int[]> a;
    unsigned int b;
    auto t = std::make_tuple(std::move(a), b); 
    return std::move(t);
}

int main()
{
    foo();
}
like image 941
akappa Avatar asked Nov 01 '25 05:11

akappa


1 Answers

I would think it should compile: the result from std::make_tuple() is a temporary std::tuple<T...> and it is supposed to move construct its members. More precisely, std::tuple<T...>'s move constructor is defaulted which should result in memberwise move construction.

Clearly, there is no real need to assign the result of std::make_tuple() to t. If you choose to introduce this variable, you shouldn't std::move(t) when returning: when the expression in a return statement is a local variable, it is treated as if it is an rvalue anyway. The extra std::move() inhibit copy/move elision, however.

like image 194
Dietmar Kühl Avatar answered Nov 02 '25 21:11

Dietmar Kühl