Can I use "this" with delegating constructors?

94 Views Asked by At

C++11 introduced the possibility of delegating construction from one constructor to another - "delegating constructors".

But - when doing that, can we use the this pointer? e.g. as an argument to one of the constructors we're delegating to? It's not trivial to assume that we can while the "real constructor" has not actually been invoked yet.

1

There are 1 best solutions below

10
einpoklum On

For a definitive answer one would need to read the standard (and even there it might not be entirely clear, see @BenjaminBanner's comment). But in practice - yes, apparently we can use this in constructor delegation.

The following example:

#include <iostream>

struct A {
    A(int x_, void* p_) : x(x_), p(p_) { }
    A(void* p_) : A(0, p_) { }
    A() : A(this) { }
    int x;
    void* p;
};

int main() {
    A a;
    std::cout << "&a == "  << &a  << "\n";
    std::cout << "a.p == " << a.p << "\n";
}

compiles (GodBolt) with all of GCC, clang and MSVC. They do not warn about doing this, even with -Wall -Wpedantic -Wextra or /W4 for MSVC.

It also runs (coliru.com) and produces the expected output (at the link you have the g++-compiled version, clang++ can be checked there as well).