简体   繁体   中英

c++11 standard-layout - using same access control

I thought that the whole point of PODs (c++11, trivial + standard-layout) is to make sure the type is compatible with C.

Given the following code:

// that one is a standard layout, and trivial which makes it a c++11 POD
struct Bar
{
public:
  int x;
public:
  int y;
};

AFAIU, compiler might reorder x and y. Wouldn't that break compatibility with C?

Why that 98/03 POD definition relaxation in c++11 considered to be a good idea?

AFAIU, compiler might reorder x and y. Wouldn't that break compatibility with C?

In C++03, it can. In C++11 it cannot. C++11's standard layout rules only require that all of the members have the same access control. They don't have to be declared in the same access control region.

Why that 98/03 POD definition relaxation in c++11 considered to be a good idea?

I think you're misunderstanding things. The C++11 rules allow more types to be standard-layout (and thus potentially layout-compatible with C types), not less. Thus, there's no real downside to relaxing the rules.

I thought that the whole point of PODs (c++11, trivial + standard-layout) is to make sure the type is compatible with C.

Not exactly the whole point of it, but yes, that is one of the properties of PODs.

 // that one is a standard layout, and trivial which makes it a c++11 POD

Correct.

AFAIU, compiler might reorder x and y. Wouldn't that break compatibility with C?

We already established it is a POD, which means the compiler will maintain compatibility with C. Maintaining compatibility with C does not break compatibility with C.

Why that 98/03 POD definition relaxation in c++11 considered to be a good idea?

Because it doesn't break anything.

The point of POD is not just to make sure the type is compatible with C - note that a type with an access specifier ( public , private , etc.) is by definition not compatible with C since C doesn't have access specifiers. The main property of a POD type is that it can be memcpy'ed around.

Having more than one access specifier in a C++ type does permit the compiler to lay out the type in a non-specified way, and that's been true for a while (it's not new with C++11):

From C++03 9.2/12

Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1).

However, that doesn't make a type a non-POD - it can still be a POD, just not one that can be portably expressed in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM