Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 931
Stanly Avatar asked Jan 14 '16 00:01

Stanly


2 Answers

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 deleted 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.

like image 66
5gon12eder Avatar answered Nov 01 '22 07:11

5gon12eder


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.

like image 42
Sam Varshavchik Avatar answered Nov 01 '22 08:11

Sam Varshavchik