问题
#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