Passing a reference to a C++ constructor -
i have this code:
#include <iostream> using namespace std; struct x { int = 1; }; struct y { x &_x; y(x &x) : _x(x) {} }; // intentionally typoed version of y, without reference in constructor struct z { x &_x; z(x x) : _x(x) {} }; int main() { x x; y y(x); z z(x); cout << "x: " << &x << endl; cout << "y.x: " << &y._x << endl; cout << "z.x: " << &z._x << endl; }
i maintain finding myself forgetting &
in constructor of classes of format.
this outputs following:
x: 0xbfa195f8 y.x: 0xbfa195f8 z.x: 0xbfa195fc
why behaviour different in case of y
, z
?
and why not error initialize x &_x
fellow member instance of type x
in constructor of y
?
a re-create of object created when constructor called, hence different output z.x. lifespan of object limited - exists in constructor. undefined behavior , reference come invalid.
to prevent such behavior in applications practice mark re-create constructor , assignment operator private.
c++ reference
No comments:
Post a Comment