Tuple with const noncopyable element

I need to create std::tuple<const XYZ,...> where XYZ is not copied . Is something like this possible? My current code

 auto test() -> std::tuple<const XYZ> { return std::make_tuple(XYZ()); } 

leads to C2248 in Visual Studio 2010 ... which I find pretty dubious since I am building a tuple with R-Value, so I would suggest that move-construction will start ...

+4
source share
1 answer

Your problem is that this element is not copyable and const . The const XYZ element behaves as a member of const XYZ ; on 5.2.5p4 access to the const XYZ element by the value x will give the value x with qualification of the union cv, that is, with the effective type const XYZ && . This type is not suitable as an argument for the XYZ move constructor, so the remote / private copy constructor will be called instead.

Another way to look at this is that the move constructor (for example, the move constructor std::tuple<...> ) must make sure that its argument remains in an undefined, but valid state. Having made the const element, you said that the only valid state for this element is the state with which it is constructed, so the move constructor cannot go from it, even if it is contained in the value x.

A workaround would be to define the const move constructor and const_cast its argument for delegation to the move constructor:

 XYZ(const XYZ &&xyz): XYZ(const_cast<XYZ &&>(xyz)) {} 

Interestingly, with gcc-4.7.2, it is enough to simply declare the const move constructor; by RVO, the actual call to the const constructor can be canceled. Do not rely on this.

+2
source

Source: https://habr.com/ru/post/1437882/


All Articles