Why does an in-place member initialization use a copy constructor in C++11?
Asked Answered
N

2

25

I'm a little bit confused about the following code:

struct A {
  std::atomic<int> a = 0;
};

Which gives an error:

copying member subobject of type 'std::atomic' invokes deleted constructor

But almost the same code does work:

struct A {
  std::atomic<int> a = {0};
};

Okey, if the first variant requires the copy constructor, then it have to use operator=(). But wait! This operator perfectly works without the copy constructor:

A a;
a.a = 1;

Can anyone explain how both of the in-place initializations are expanded in terms of simple operations? Why the first one requires copy constructor?

Noddle answered 11/2, 2014 at 17:18 Comment(6)
Keep in mind, copy assignment does not use the copy constructor. std::atomic<int> a = 0 involves the copy constructor. a.a = 1 is merely assignment, it's not even copy assignment. I can't answer though, because I don't know why std::atomic<int> a = {0} succeeds, I would have expected that to fail.Boob
@MooingDuck I always thought, that std::atomic<int> a = 0, should be equal to std::atomic<int> a(0) - without copy constructor, but looks like it's not.Noddle
std::atomic<int> a = 0 would require a copy constructor syntactically, and so the C++ spec says this syntax requires the copy constructor to be available. However, using the copy constructor would be unnecessary overhead, so the C++ spec also says that the copy constructor may be elided, which makes it behave identically to std::atomic<int> a(0);. Note that this behavior still requires the copy constructor to be theoretically usable.Boob
@MooingDuck thanks for explanation, I didn't know that. Your comment contains a half of an answer.Noddle
Yeah, I'd started as an answer, but then moved it to the comments because I only knew half :/Boob
@MooingDuck It doesn't strictly require a copy constructor, a move constructor suffices for copy-initialization.Meter
M
23

All references are to N3797, the C++1y current working draft. §8.5 Initializers [dcl.init]/15 states:

The initialization that occurs in the form

T x = a;

as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.5.1) is called copy-initialization. [ Note: Copy-initialization may invoke a move (12.8). —end note ]

So the declaration:

std::atomic<int> a = 0;

is performing copy-initialization. According to 8.5/17:

The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.

The destination type here is std::atomic<int> and the source type is int (i.e., decltype(0)). To determine the semantics of the initialization, we have to determine which of paragraph 17's bullets applies:

  • If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).
  • If the destination type is a reference type, see 8.5.3.
  • If the destination type is an array of characters, an array of char16_t, an array of char32_t, or an array of wchar_t, and the initializer is a string literal, see 8.5.2.
  • If the initializer is (), the object is value-initialized.
  • Otherwise, if the destination type is an array, the program is ill-formed.
  • If the destination type is a (possibly cv-qualified) class type:
    • If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, ... [does not apply, source type is int]
    • Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the cv-unqualified version of the destination type. The temporary is a prvalue. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8.
  • ...

There we are. The initializer expression - 0 - is converted into a std::atomic<int> via the creation of a temporary object initialized with the std::atomic<int>(int) constructor. That temporary object is used to direct-initialize the original std::atomic<int> object. The other of the "(possibly cv-qualified) class type" bullets that we ignored before now applies:

  • If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

Recall that the new initializer is a prvalue std::atomic<int>. Overload resolution determines that there is no appropriate std::atomic<int> constructor that accepts a single argument std::atomic<int>&& (std::atomic<int> is not movable or copyable) and diagnoses the program as ill-formed.

For the second part of the question,

std::atomic<int> a = {0};

is again copy initialization per 8.5/15. This time, however, the very first bullet of 8.5/17 applies:

  • If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).

For list-initialization, we must look to 8.5.4/3:

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

  • If T is an aggregate, aggregate initialization is performed (8.5.1).
  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • Otherwise, if T is a specialization of std::initializer_list<E>, a prvalue initializer_list object is constructed as described below and used to initialize the object according to the rules for initialization of an object from a class of the same type (8.5).
  • Otherwise, if T is a class type, constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution (13.3, 13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed.
  • ...

std::atomic<int> is a class type, not an aggregate or initializer_list specialization, so constructors are considered. The std::atomic<int>::atomic(int) constructor will be selected as a perfect match and is used to initialize the object.

Meter answered 11/2, 2014 at 19:8 Comment(6)
You want standard references? There's a language-lawyer answer.Meter
Sadly, the relevant references appear to be missing? §9.2 ad 4 "A brace-or-equal-initializer shall appear only in the declaration of a data member. (For static data members, see 9.4.2; for non-static data members, see 12.6.2)."?Deflagrate
@Deflagrate The difference in the behavior of the two non-static data member initializers has nothing to do with the fact that they are non-static data member initializers.Meter
After having read all that, I concur. However, it is relevant context, and the fact the semantics are the same is only specified in §12.6.x (about 3 locations). It's nice to explicitely mention that. (You already had my +1)Deflagrate
What about the form std::atomic<int> a {0}, without the equals sign? My reading of [dcl.init] is that this is list-initialization, equivalent to = {0}. But GCC appears to distinguish the two, giving a compilation error for the one without the equals sign due to a deleted copy constructor, whereas Clang does not.Tigrinya
Can anyone answer @Tigrinya ? I'm interested as well (even if GCC 5.4.0 now seems to accept both.Danielladanielle
B
7

Let consider the first case

struct A {
  std::atomic<int> a = 0;
};

For this initialization to be successful, there needs to be an accessible copy constructor. But the copy constructor is defined as deleted.

atomic(const atomic&) = delete;

So the compiler issues an error.

In the second case

struct A {
  std::atomic<int> a = {0};
};

where an initializer list is used the copy constructor is not required. The compiler searches for a constructor that accepts one int argument and such constructor indeed exists, so it is called.

constexpr atomic(T) noexcept;

or if to substitute template parameter for type int

constexpr atomic(int) noexcept;

According to the C++ Standard if a class has no constructor with the first parameter of type std::initializer_list (when an initializer list is specified) then

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

Otherwise, if T is a class type, constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution (13.3, 13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed.

In the last case

A a;
a.a = 1;

this uses an assignment operator

T operator=(T) noexcept;

or if to substitute template parameter for type int

int operator=(int) noexcept;

So there is no problem.

Backblocks answered 11/2, 2014 at 17:33 Comment(6)
I think that assignment operator at the bottom is slightly ambiguous, I personally would be happier if it were changed to int operator=(int) noexcept, which clarifies that it's not a copy-constructor. Thoughts?Boob
@Mooing Duck Do you mean that instead of template parameter I should use argument int?Backblocks
Sorry, but it seems to me, that you just expressed in english the compiler's actions :) You don't explain, why the compiler behaves this way and not another one. Actually, why the copy constructor is not required in the second case?Noddle
@Noddle In the second case copy constructor is not used due to the rules how initializer lists are processed by constructors. I will update my post.Backblocks
@abyss.7: These are the rules from the C++ spec, were you desiring quotes? We can do that if that's what you were expecting.Boob
@MooingDuck I was really expecting the expanding of initializations, but in the first case there is no expanding - just some C++ spec rules about accessibility of copy constructor. So, now I'm less confused. If the second case can be explained in the terms of spec rules, then let it be so. It's hard to expect some specific explanation, if you don't know how it works.Noddle

© 2022 - 2024 — McMap. All rights reserved.