0

Can i safely use this pointer outside class before its constructor finished (i don't mean virtual function call from constructor)?

I mean something like 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 the following warning when i tried to compile this code in MSVC-11.0

warning C4355: 'this' : used in base member initializer list

And what about 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 any quote from standard.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • About the warning: what if a member of `Bar` is used by `Foo` *before* the member's constructor is called? That could lead to undefined behavior. – Mark Garcia Feb 14 '13 at 04:19
  • I'm not sure how to tag this properly (the FAQ doesn't help), but this seems like a borderline duplicate. (http://stackoverflow.com/questions/2516960/c-using-this-pointer-in-constructors) – Pseudonym Feb 14 '13 at 04:21

1 Answers1

1

that would work while Foo ctor or bar function in second example do not call smth that refer to still uninitialized members of Bar/Foo. I'll transform you 1st example a little to 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;
};
zaufi
  • 6,811
  • 26
  • 34