Guaranteed copying of text and Nonmoveable {Nonmoveable {}}

I found that GCC 7 implemented a guaranteed copy instance, and I tried the code below in wandbox :

#include <iostream> struct NonMovable { NonMovable() noexcept = default; NonMovable(NonMovable&&) noexcept = delete; NonMovable& operator=(NonMovable&&) noexcept = delete; }; NonMovable Make() { return {}; } int main() { //[[maybe_unused]] const auto x = Make(); //const auto z = NonMovable{}; [[maybe_unused]] const auto y = NonMovable{NonMovable{}}; } 

And I got a compilation error:

 prog.cc: In function 'int main()': prog.cc:20:60: error: use of deleted function 'NonMovable::NonMovable(NonMovable&&)' [[maybe_unused]] const auto y = NonMovable{NonMovable{}}; ^ prog.cc:6:5: note: declared here NonMovable(NonMovable&&) noexcept = delete; ^~~~~~~~~~ 

According to cppreference :

During initialization, if the initializer expression is prvalue and the cv-unqualified version of the source type is the same class as the destination class, the initializer expression is used to initialize the target:
T x = T(T(T())); // only one call to default constructor of T, to initialize x

Therefore, I think it should be equal to const Movable y{}; . What's wrong?

+6
source share
1 answer

Initializing the list does not give precise control over what is happening. Basically, the committee guessed what the programmer might want to do most likely and assigned the appropriate values.

If you want to have precise control, use listless initialization. To do this, your test file must work definitely.

If you stick to list initialization, then for aggregates I think the current version of the project will do this and apply guaranteed copying of "elision" because they say

If T is a cumulative class, and in the initialization list there is one element of type cv U, where U is T or a class derived from T, the object is initialized from this element (by copy initialization for the copy list, initialization or direct initialization to initialize the direct list )

In addition, you can get what you want in a future edition of the standard or in the resolution of a defect report even for non-units. I believe your class is aggregate, so it should compile. But maybe something is missing for me there.

+1
source

All Articles