Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::string a standard layout type?

Tags:

c++

c++11

Taking the example from here: trivial vs. standard layout vs. POD

The following code passes:

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

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

Yet the following does not:

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

So if all it takes for a type not to be a standard layout, then how could std::string possible be one?

like image 369
Sam Kellett Avatar asked Sep 16 '25 19:09

Sam Kellett


2 Answers

Let's look at the actual rules for standard layout:

[C++14: 9/7]: A standard-layout class is a class that:

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

std::string probably has no public data members (what would they be?), which is where you tripped up with your T (since now you have both private and public data members; see emboldened passage).

But as far as I can tell there is no actual requirement for std::string to be standard layout. That's just how your implementation has done it.

like image 109
Lightness Races in Orbit Avatar answered Sep 18 '25 10:09

Lightness Races in Orbit


According to the requirement of StandardLayoutType:

Requirements

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

That's why T failed to be standard layout type. std::string is just satisfying the requirements.

like image 40
songyuanyao Avatar answered Sep 18 '25 08:09

songyuanyao