A little help to understand the execution of a C ++ code stream

I read about the constructor initialization order in C ++ Super-FAQ from the C ++ programming language website . Here is the following code.

#include <iostream>
class Y {
public:
  Y();
  void f();
};
Y::Y()      { std::cout << "Initializing Y\n"; }
void Y::f() { std::cout << "Using Y\n"; }
class X {
public:
  X(Y& y);
};
X::X(Y& y) { y.f(); }
class Z {
public:
  Z();
protected:
  X x_;
  Y y_;
};
Z::Z() 
  : y_()
  , x_(y_)
{ }
int main()
{
  Z z;
  return 0;
}

The printed sequence of this code is:

Using y

Initialization Y

, , , Z y_ Y x_ X. , , , Y:: f(), Y, std:: cout < " Y\n";.

+4
2

X x_ Y y_ class Z, defintion x_. , Z::Z() : y_(), x_(y_) {}, x_.

y_ , , vtable, . X segfault. , .

class Z {
public:
  Z();
protected:
  Y y_;
  X x_;
};

x_ y_, y_, x_.

.

: ++ , , . , .

Y* p = 0;
X x(reinterpret_cast<Y&>(p));

, , . f , segfault.

+4

Z :

X x_;
Y y_;

:

Z::Z()
    : y_()
    , x_(y_)
{ }

, . . this

, . undefined behavoiur, .

, , "// Bad: should have listed x_ before y_"

, y_ (Y:: f()) (Y:: Y()).

+2

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


All Articles