10

The following code segfaults under gcc-4.9, 5.4, and 6.3 with std=c++11, but compiles and runs fine under clang-3.7, and VS2015 Update 3.

struct A
{
    int Func() { return x++; }
    int x = 5;
};

struct B
{
    B(int) {}
};

struct Derived : public virtual A, public B
{
    Derived()
      : A()
      // , B(this->Func()) // This works!
      , B([this](){ return this->Func(); }()) // But this segfaults.
    {
    }
};

int main()
{
    Derived c;
}

Is this a bug in gcc? Removing virtual inheritance fixes the segfault.

Andrew
  • 277
  • 3
  • 11
  • 5
    `this` refers to an instance of `Derived`. But there is no `Derived` until its construction actually starts, yet, `this` needs to be evaluated in order to construct the base class, but until all the base classes are constructed, there is no `Derived`. Undefined behavior. – Sam Varshavchik May 02 '17 at 23:47
  • @SamVarshavchik: You should write it as an answer quoting the standard. That would be better !!! – Destructor May 03 '17 at 05:57
  • I actually tried to find something that, but, after a few minutes looking I couldn't actually find anything. I guess until lambdas came around you couldn't have a situation where you could have a `this` before the object actually exists; hence this is not explicitly spelled out. – Sam Varshavchik May 03 '17 at 11:57
  • 1
    Hmmm. It still seems strange to me. The example in the standard quoted in http://stackoverflow.com/questions/4006160/in-c-initialize-a-class-member-with-this-pointer-during-construction explicitly uses the this pointer, when referring to a base member. To me that seems like the this pointer is valid, and should refer to the base class when captured, so it should be fine. – Andrew May 03 '17 at 12:10
  • 2
    Looks like this is a bug. C++14 12.7.3 is fairly explicit that this should be allowed. – Vaughn Cato May 09 '17 at 03:21

1 Answers1

2

This has been filed as a bug with gcc, and confirmed.

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81051

Andrew
  • 277
  • 3
  • 11