mercredi 10 juillet 2019

Why does std::vector work with incomplete types in class definitions?

The following question came up:

The c++ standard seems to say, that std::vector requires a complete type to work. (See https://en.cppreference.com/w/cpp/container/vector ) Then, why does the following code still compile?

#include <vector>

struct parent;

struct child
{
    std::vector<parent> parents; //parent is incomplete here!
};

struct parent
{
    std::vector<child> children;
};

This seems counterintuitive. If std::vector requires a complete type, then std::vector<parent> should not compile because only its forward declaration is known inside the class definition of child.

  • Is this behaviour something special about class definitions?
  • Did I get it wrong, and std::vector does not require a complete type?
  • Or, is this just a fluke? In that technically this isn't allowed, but it works for all implementations anyways...

EDIT

There seems to be a difference between c++11 and c++17. I would like to understand the c++11 version.

Aucun commentaire:

Enregistrer un commentaire