Edit: Code compiling now. Also added more detailed code to depict exact scenario.
Is it safe to pass this pointer in the initializer list ? Are there any chances of segmentation fault in case object methods are called before object is constructed? Or better to pass this pointer in constructor ? following are the example classes.
#include "iostream"
using namespace std;
class Observer
{
public:
Observer() = default;
protected:
Observer(const Observer& other) = default;
Observer(Observer&& other) = default;
Observer& operator=(const Observer& other) = default;
Observer& operator=(Observer&& other) = default;
public:
virtual ~Observer() = default;
virtual void method() const
{
}
};
class ThirdClass
{
public:
ThirdClass(const Observer* const first) : firstPtr{first}
{
// register for some events here.
// that events will call someMethod and someMethod is calling FirstClass's method, before initializer list of FirstClass gets executed.
}
void someMethod()
{
firstPtr->method();
}
static ThirdClass& getInstance(const Observer* const first)
{
static ThirdClass instance = ThirdClass(first);
return instance;
}
private:
const Observer* firstPtr{};
};
class FirstClass: public Observer
{
public:
FirstClass():third(ThirdClass::getInstance(this))
// init
// init
// some big initializer list which will take time to inilialize
{
}
virtual void method() const override
{
}
private:
const ThirdClass& third;
};
int main()
{
FirstClass firstObj;
return 0;
}
Assume the scenario like, Initializer list of FirstClass
is very big and before its complete execution, event is fired(For which, third class is registered) and that event calls the someMethod()
of ThirdClass
. Does this will cause undefined behavior. Or there are not at all chances of Undefined Behaviour ?
PS: there is similar question here Is it safe to use the "this" pointer in an initialization list? But that mentions some parent child relationship.