How function call is working on an unitialized data member object in constructor's initilalizer list

对着背影说爱祢 提交于 2020-01-07 03:07:08

问题


Consider below program,

#include <iostream>

using namespace std;

class A
{
public:
    A() { cout << "A constructor\n"; }
    void f()
    {
       cout << "A used\n";
       this->i++;
    }
private:
    int i;
};

class B
{
public:
    B(A & a1)
    {
        cout << "B constructor\n";
        a1.f();
    }
};

class Z
{
public:
    Z() :  a_(), b_(a_) {}
private:
    B b_;
    A a_;
};

int main() {
    Z z;
    return 0;
}

Below is output it produces,

B constructor
A used
A constructor

My Question,

Since data member objects are created in order of their declaration in class, hence b_ will be created first. But how it is able to call a function on data member a_ which is still not created? Does compiler performs some kind of optimization to translate call to f() to a plain function call? If yes, then how this->i++ is working?


回答1:


The compiler won't fight you when you explicitly instruct it to pass a reference to an uninitialized object somewhere. After all, the function you pass it to may be used to actually initialize the object.

However, accessing uninitialized data, e.g., your this->i++;, results in undefined behavior.



来源:https://stackoverflow.com/questions/34011947/how-function-call-is-working-on-an-unitialized-data-member-object-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!