jeudi 25 juin 2015

std::vector on forward declared type

The following code seems to work correctly on Clang++ and GCC:

#include <vector>

class A {
private:
    int i;
    std::vector<A> children;
public:
    A& add();
};

A& A::add() { children.emplace_back(); return children.back(); }

int main() {
    A a;
    A& a2 = a.add();
}

When the data member std::vector<A> is declared, A is still an incomplete type. Same when using std::vector<B> and B was only forward declared with class B;. It should work with std::vector since it only contains a pointer-to-A.

Is this guaranteed to work, or undefined behavior?

Aucun commentaire:

Enregistrer un commentaire