Why is std :: string the standard layout type?

Example from here: Trivial and Standard Layout vs POD

The following code goes through:

struct T {
public:
    int i;
private:
    int j;
};

static_assert(! std::is_standard_layout<T>::value, "");

      

However, the following:

static_assert(! std::is_standard_layout<std::string>::value, "");

      

So, if all it takes for a type to be non-standard layout, then how can std :: string be one?

+3


source to share


2 answers


Look at the actual rules for the standard layout:

[C++14: 9/7]:

A standard layout class is a class that:

  • has no non-static data members such as a non-standard class layout (or an array of such types) or a reference,
  • has no virtual functions (10.3) and no virtual base classes (10.1),
  • has the same access control (section 11) for all non-static data members ,
  • does not have base classes of non-standard layout,
  • either has no non-static data members in the derived class itself and at most one base class with non-static data members, or has no base classes with non-static data members, and
  • does not have base classes of the same type as the first non-static data member.


std::string

probably doesn't have the items public

(what would they be?) where you ran into yours T

(since you now have both members private

and public

, see the bold passage).

But as far as I can tell, there is no actual requirement for a std::string

standard layout. This is how your implementation did it.

+9


source


As per the StandardLayoutType requirement :

Requirements

  • All non-static data members have the same access control
  • ...


This is why T

it was not a standard layout type. std::string

just meets the requirements.

+2


source







All Articles