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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With