Uniform initialization fails to copy when object has no data members

回眸只為那壹抹淺笑 提交于 2019-11-26 14:48:53

问题


In updating some code to use uniform initialization, I thought it would be a drop-in modern substitue for the now "old style" parentheses style. I know this isn't always the case (obvious example, vector<int>) but I've stumbled over another difference that I don't understand.

class Object {
    public:
        Object() = default;
        Object(const Object&) = default;
};

int main() {
    Object o;
    Object copy{o}; // error
    Object copy2(o); // OK
}

fails to compile under clang3.5 with the error: (also fails under gcc)

error: excess elements in struct initializer

There are two different changes to Object that make this work. Either adding a data member to it, or giving it an empty copy constructor body

class Object {
    private:
        int i; // this fixes it
    public:
        Object() = default;
        Object(const Object&) { } // and/or this fixes it as well
};

I don't see why these should make a difference.


回答1:


Johannes's answer is useful, but let me elaborate on why it currently happens.

Both of the changes you describe affect your class by making it go from an aggregate to not an aggregate. See C++11 (N3485) § 8.5.1/1:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

A constructor with a definition of = default is considered not user-defined.

Then, going down to list-initialization in § 8.5.4, we see:

List-initialization of an object or reference of type T is defined as follows:

  • If T is an aggregate, aggregate initialization is performed

And then a bunch of "Otherwise..." sections. Thus, changing either of these allows a constructor to be called instead of performing aggregate initialization.

The new proposed standardese for the list-initialization definition (as viewable in Johannes's link) provides a prioritized case of a single element in the list, and it having a type of (or really close to) the type of the object being initialized. Aggregate initialization would then be top priority after that.




回答2:


This is a known bug and will hopefully be fixed in C++17 (not for C++14, see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1467). Your struct is an aggregate, so to initialize it with {someElement} there needs to be at least one data member, as you have discovered. Try providing an operator int(); and you will see it compiles.



来源:https://stackoverflow.com/questions/21340801/uniform-initialization-fails-to-copy-when-object-has-no-data-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!