Passing this as argument to members in C++

c++

Solution

The potential problem is that `this` points to an object that has not been fully constructed. So for example if you had this:

template<class T>
struct fun
{
    fun(T* pointer) : memberPointer(pointer)
    {
        memberPointer->callMethod(); //this is 2nd to execute
    }

    T* memberPointer;
};

struct gun
{
    gun() : member(this) //this is 1st to execute
    {
       ptr = new char(); // this is 4rd to execute unless earlier UB prevents execution
    }
    void callMethod()
    {
       printf("%s", ptr); //this is 3rd to execute, you get UB here
    }
   fun<gun> member;
   char* ptr;
};

you would run into undefined behavior because you would pass a pointer to a not fully constructed object where only a pointer to a fully constructed object should be passed. I intentionally crafted some crappy code with UB to be more convincing, in real life you won't necessarily have UB as a problem, sometimes all the objects will be in valid states so you will get some really subtle initialization order bugs.

That's not your case. Your case is fine - you don't care that the object is not yet fully constructed. However you should be careful when changing your code so that you don't get into scenario as above.

Problem

I want to pass `this` as argument to member variable like this: ``` template<class T> struct fun { fun(T* pointer) : memberPointer(pointer) { } T* memberPointer; }; struct gun { gun() : member(this) { } fun<gun> member; }; ``` In Visual Studio I have next warning: `warning C4355: 'this' : used in base member initializer list` Can you please explain why is it wrong to do this? I just store the pointer in member constructor to use it later to call some `gun` functions from `fun`.

Original source