C ++ class compilation

Why the next compilation?

class A{ A(){ A* a = new A() ; } } ; 

Should it not work for the same reason, something like unsuccessful?

 class A{ A obj; } ; 
+5
source share
2 answers
 class A{ A obj; } ; 

is a recursive bomb because size A based on A Obviously this is not possible. A does not know how big A and never will be. This is easy to catch at compile time.

 class A{ A(){ A* a = new A() ; } } ; 

It is still a recursive bomb, but it will explode at run time, making it a logical mistake, not a syntax error. The compiler may issue a warning.

The secret here is that the functions defined in the class through the magic of the built-in functions ( [dcl.fct.spec] point 3, but apparently this is point 4 under [dcl.inline] in later drafts of the standard) and compiled after the class is defined, when it is used in other code (or none at all, as the MM indicates below if the function is never used).

Since the function will be moved outside the class definition before compiling it, the size A is known at the time the function is compiled, so it can be built safely.

As for A* a , this is just a pointer. The size is baked directly and has no special requirements.

+4
source

Ad

 class A{ A obj; } ; 

is illegal because you declare infinite storage this way. Note that containing a static field of a native class or a non-static base class is legal.

 class A { public: static A a; }; AA::a = A(); class B : A { A obj; } 

Such things as

 class A{ A(){ A* a = new A(); } }; 

possible, regardless of what is declared inside the method, this is another repository. This is legal with the help of language rules, but semantically it is wrong; calling such a constructor will cause infinite recursion.

+1
source

Source: https://habr.com/ru/post/1265719/


All Articles