c++11 in-class member initialization with this

120 views Asked by At

I have a quick question in gcc 4.8 with the flag -std=c++11 enabled. I can do this and it works fine.

class Test;
class StupidClass {

public:
    StupidClass(Test *test) {}
};

class Test {
    StupidClass c = StupidClass(/*this is the part in question*/ this);
};

and i wanted to know if this is valid c++11 having "this" in an in-class member initialization like this.

2

There are 2 answers

0
Kerrek SB On BEST ANSWER

If you write

struct Foo
{
    Bar bar { this };
};

that is no different from:

struct Foo
{
    Foo() : bar(this) { }
    Bar bar;
};

So if the second one makes sense, so does the first.

1
galop1n On

it is valid but you need to be careful as this is not yet fully valid. Storing a pointer or reference is fine, using a member declared before the one receiving this is fine too.