jeudi 21 mars 2019

GCC : C++11 inline object initialization (using "this") does not work when there is a virtual inheritance in hierarchy

C++11 inline object initialization does not work (in GCC) when this pointer is used in initialization and there is a virtual inheritance in hierarchy. Can this be a bug is GCC (because it works in CLang)? Or a gap in C++11 standard itself?

Example (one can try it in here), when below code is compiled with GCC:

FieldIndex m_inB{"inB", this};

does not get executed. But it gets executed when compiled with CLang.

WORK AROUND : Derive A from FieldIndexContainer as virtual

#include <string.h>
#include <iostream>
#include <list>
using namespace std;

class FieldIndexContainer
{
public:
    class FieldIndex
    {
    public:
        FieldIndex( const std::string& fieldName, FieldIndexContainer* owner) 
        {
            cout << "FieldIndex called = " << fieldName << endl;
        }
    };  
};

class A : public FieldIndexContainer
{
public:
    FieldIndex m_inA{ "inA", this};
};

class Mid : virtual public A {};

class B : virtual public Mid
{
public:     
    FieldIndex m_inB{"inB", this};
};

int main () 
{
    B* b = new B;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire