简体   繁体   中英

C++ auto with member initializer syntax and deleted copy constructor

class A
{
    int a;

public:

    A(const A&) = delete;
    A& operator=(const A&) = delete;

    A() : a {0}
    { }
};

int main()
{
    auto a = A {};
}

The above code does not compiles and i get the following error: C2280 'A::A(const A &)': attempting to reference a deleted function

I am using visual studio 2015 compiler. My understanding is with member initialization syntax compiler should directly use the default constructor which is what happens when there is no auto and in main i use A a{} . So i was wondering what is the deal with auto in this case.

auto a = A {};

is only valid if A is copy constructible or move constructible. The fact that you use auto is irrelevant. The same would be true for

A a = A {};

as well.

Declaring a copy constructor – even a delete d one – inhibits implicit declaration of a move constructor so your type A is neither copy constructible nor move constructible. If you add the line

A(A&&) = default;

to the body of A , the code should compile again.

In practice, the compiler will not actually call any copy or move constructor in this case and simply construct the object right in a . But the language rules demand that it must still reject the code which makes sense because whether a piece of code is allowed or not should not depend on an optional compiler optimization.

This behavior will (most likely) change in C++17.

Your understanding is correct, so let's see what's happening here, one step at a time.

A {};

As you said, member initialization syntax, completely kosher here.

auto a = (expression of some kind)

And then you're constructing auto a . After performing type inference, this becomes equivalent to...

A a = (expression of some kind)

Which looks like a copy constructor. Which you deleted.

you should use auto this way:

auto a = new A();

if you don't want to use auto this is c++11 way:

A a{};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM