Tuesday, 15 May 2012

c++ - this pointer and constructor -



c++ - this pointer and constructor -

can safely utilize pointer outside class before constructor finished (i don't mean virtual function phone call constructor)?

i mean this:

#include <iostream> class bar; class foo { public: foo(bar* bar); }; class bar { public: bar() : instance(this) {} void foo() { std::cout << "bar::foo() \n"; } private: foo instance; }; foo::foo(bar* bar) { bar->foo(); // ub or not } int main() { bar instance; }

i've got next warning when tried compile code in msvc-11.0

warning c4355: 'this' : used in base of operations fellow member initializer list

and such code?

#include <iostream> class foo; void bar(foo* instance); class foo { public: foo() { bar(this); } void foo() { std::cout << "foo::foo() \n"; } }; void bar(foo* instance) { instance->foo(); // ub or not } int main() { foo instance; }

i can't find quote standard.

that work while foo ctor or bar function in sec illustration do not phone call smth refer still uninitialized members of bar/foo. i'll transform 1st illustration little demonstrate:

class bar { public: bar() : instance(this),zzz(123) {} void foo() { std::cout << "bar::foo(): garbage in zzz=" << zzz << "\n"; } private: foo instance; int zzz; };

c++

No comments:

Post a Comment