Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 allows in-class initialization of non-static and non-const members. What changed?

Before C++11, we could only perform in-class initialization on static const members of integral or enumeration type. Stroustrup discusses this in his C++ FAQ, giving the following example:

class Y {   const int c3 = 7;           // error: not static   static int c4 = 7;          // error: not const   static const float c5 = 7;  // error: not integral }; 

And the following reasoning:

So why do these inconvenient restrictions exist? A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

However, C++11 relaxes these restrictions, allowing in-class initialization of non-static members (§12.6.2/8):

In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then

  • if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;
  • otherwise, if the entity is a variant member (9.5), no initialization is performed;
  • otherwise, the entity is default-initialized (8.5).

Section 9.4.2 also allows in-class initialization of non-const static members if they are marked with the constexpr specifier.

So what happened to the reasons for the restrictions we had in C++03? Do we just simply accept the "complicated linker rules" or has something else changed that makes this easier to implement?

like image 361
Joseph Mansfield Avatar asked Dec 01 '12 18:12

Joseph Mansfield


People also ask

Why is initializing a class member variable during declaration not permitted?

The main reason is that initialization applies to an object, or an instance, and in the declaration in the class there is no object or instance; you don't have that until you start constructing.

Why don't we initialize the static data member in the constructor of the class?

1) Static variables are property of the class and not the object. 2) Any static variable is initialized before any objects is created. That's why compiler don't allow to define static variable inside constructor as constructor will be called when a object is created.

Why we Cannot initialize data members within the class?

Answer: When we declare/write a class, there is no memory allocation happens for data members of a class, so, we cannot store data into data members. The memory gets allocated for data members only when we create objects of a class. So, initialization of the variable happens once object of the class get created.

How do you initialize a const member of a class?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.


2 Answers

The short answer is that they kept the linker about the same, at the expense of making the compiler still more complicated than previously.

I.e., instead of this resulting in multiple definitions for the linker to sort out, it still only results in one definition, and the compiler has to sort it out.

It also leads to somewhat more complex rules for the programmer to keep sorted out as well, but it's mostly simple enough that it's not a big deal. The extra rules come in when you have two different initializers specified for a single member:

class X {      int a = 1234; public:     X() = default;     X(int z) : a(z) {} }; 

Now, the extra rules at this point deal with what value is used to initialize a when you use the non-default constructor. The answer to that is fairly simple: if you use a constructor that doesn't specify any other value, then the 1234 would be used to initialize a -- but if you use a constructor that specifies some other value, then the 1234 is basically ignored.

For example:

#include <iostream>  class X {      int a = 1234; public:     X() = default;     X(int z) : a(z) {}      friend std::ostream &operator<<(std::ostream &os, X const &x) {          return os << x.a;     } };  int main() {      X x;     X y{5678};      std::cout << x << "\n" << y;     return 0; } 

Result:

1234 5678 
like image 82
Jerry Coffin Avatar answered Sep 18 '22 03:09

Jerry Coffin


I guess that reasoning might have been written before templates were finalized. After all the "complicated linker rule(s)" necessary for in-class initializers of static members was/were already necessary for C++11 to support static members of templates.

Consider

struct A { static int s = ::ComputeSomething(); }; // NOTE: This isn't even allowed,                                                    // thanks @Kapil for pointing that out  // vs.  template <class T> struct B { static int s; }  template <class T> int B<T>::s = ::ComputeSomething();  // or  template <class T> void Foo() {     static int s = ::ComputeSomething();     s++;     std::cout << s << "\n"; } 

The problem for the compiler is the same in all three cases: in which translation-unit should it emit the definition of s and the code necessary to initialize it? The simple solution is to emit it everywhere and let the linker sort it out. That's why the linkers already supported things like __declspec(selectany). It just wouldn't have been possible to implement C++03 without it. And that's why it wasn't necessary to extend the linker.

To put it more bluntly: I think the reasoning given in the old standard is just plain wrong.


UPDATE

As Kapil pointed out, my first example isn't even allowed in the current standard (C++14). I left it in anyway, because it IMO is the hardest case for the implementation (compiler, linker). My point is: even that case is not any harder than what's already allowed e.g. when using templates.

like image 28
Paul Groke Avatar answered Sep 18 '22 03:09

Paul Groke