Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

c++ - Uniform initialization fails to copy when object has no data members

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...