Consider the following example. When bar
is constructed, it gives it's base type (foo
) constructor the address of my_member.y
where my_member
is data member that hasn't been initialized yet.
struct foo {
foo(int * p_x) : x(p_x) {}
int * x;
};
struct member {
member(int p_y) : y(p_y) {}
int y;
};
struct bar : foo
{
bar() : foo(&my_member.y), my_member(42) {}
member my_member;
};
#include <iostream>
int main()
{
bar my_bar;
std::cout << *my_bar.x;
}
Is this well defined? Is it legal to take the address of an uninitialized object's data member? I've found this question about passing a reference to an uninitialized object but it's not quite the same thing. In this case, I'm using the member access operator .
on an uninitialized object.
It's true that the address of an object's data member shouldn't be changed by initialization, but that doesn't necessarily make taking that address well defined. Additionally, the ccpreference.com page on member access operators has this to say :
The first operand of both operators is evaluated even if it is not necessary (e.g. when the second operand names a static member).
I understand it to mean that in the case of &my_member.y
my_member
would be evaluated, which I believe is fine (like int x; x;
seems fine) but I can't find documentation to back that up either.
.
and->
operators. – Backplate.
in&my_member.y
is well defined. – Meadowlark&my_member.y
is not actually address of operator, but rather member access operator that evaluates the still-not initialized object. I should've read question more carefully. – Backplate