Member pointer to member object and declaration order

自古美人都是妖i 提交于 2019-12-11 14:08:47

问题


#include <iostream>

class FooParent
{
    public:
        FooParent(int* new_p_bar)
        {
            p_bar = new_p_bar;
        }
    public:
        int* p_bar;
};

class FooChild : public FooParent
{
    public:
        int bar;
    public:
        FooChild(int new_x)
        :FooParent(&bar)
        ,bar(new_x) \\ point of concern
            {} 
};

int main()
{ 
    FooChild foo(8);
    std::cout << foo.bar << std::endl;

}

The above example works as I want it to .i.e. link the pointer p_bar to bar. However, my concern is that I am pointing to a member whose constructor is not yet called.

Is this code valid, or does the standard have something to say about it. If not what is the alternative.

NOTE: In my application bar is an Object Bar (not int), does this have any implications?


回答1:


Look at this:

class FooParent {
    public:
        FooParent(int* new_p_bar)
        {
            p_bar = new_p_bar;
            *p_bar = 99; // this has no sense
        }
        void set99() {
            *p_bar = 99; // this - has
        }
    public:
        int* p_bar;
};

class FooChild : public FooParent
{
    public:
        int bar;
    public:
        FooChild(int new_x)
        :FooParent(&bar)
        ,bar(new_x) // point of concern
            {} 
};

int main()
{ 
    FooChild foo( 42 );
    std::cout << foo.bar << std::endl;
    foo.set99();
    std::cout << foo.bar << std::endl;
}

LWS.

I mean that if FooParent's constructor only stores a pointer to external int (or Bar - doesn't matter) then there will be no problem.

In other hand, if you'll give a copy of bar to FooParent - like this

class FooParent
{
    public:
        FooParent(Bar new_p_bar)
        {
            p_bar = new_p_bar;
        }
        void set99() {
            p_bar = 99; // this - has
        }
    public:
        Bar p_bar;
};

class FooChild : public FooParent
{
    public:
        Bar bar;
    public:
        FooChild(Bar new_x)
        :FooParent(bar)
        ,bar(new_x) // point of concern
            {} 
};

int main()
{ 
    FooChild foo( 42 );
    std::cout << foo.bar << std::endl;
    foo.set99();
    std::cout << foo.bar << std::endl;
}

LWS.

this will not work. Even if Bar will have a copy c-tor or/and assignment operator




回答2:


If you are passing pointer to member there is no undefined behavior, until you are trying to dereference it. If you want to have constructor called look into base-from-member idiom http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Base-from-Member



来源:https://stackoverflow.com/questions/15384746/member-pointer-to-member-object-and-declaration-order

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