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.