持有标准库容器的结构的POD含义 [英] POD implications for a struct which holds an standard library container

查看:67
本文介绍了持有标准库容器的结构的POD含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题最近.我的目标是了解C ++编译器如何查看包含标准库容器(例如std :: vector)的结构定义.

I came across this question recently. My goal is to understand how the C++ compiler views struct definitions which hold standard library containers such as std::vector.

Ben Voigt对链接问题的回答引用了C ++ 0x标准的以下内容:

Ben Voigt's answer to the linked question cites the following from the C++0x standard:

....

....

普通类是具有普通默认构造函数(12.1)且可轻松复制的类.

A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

[注意:特别是,琐碎可复制或琐碎的类没有虚函数或虚基 类. — 尾注]

[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes. — end note ]

标准布局类是这样的类:

  • 没有非标准布局类(或此类数组)或引用的非静态数据成员
  • has no non-static data members of type non-standard-layout class (or array of such types) or reference,

....

我几乎可以肯定,粗体字暗示以下内容是未定义的行为

I'm almost certain that the bolded text implies that the following is undefined behavior

struct A 
{
    std::vector< SomeType > myVec;
    int myC;  
    A( int c ) : myC : (c) {}
};

int main( void )
{
    A one( 1 );
    A two( 2 );

    SomeType k, z;
    one.myVec.push_back( k );
    two.myVec.push_back( z );

    memcpy( &two, &one, sizeof( A ) ); // bad juju
}

来自标准库的 any 类型也是如此,包括更简单的类型,例如std::string.鉴于其大量使用继承和模板编程,这是由于库的设计性质所致.

And the same would be the case for any type which is from the standard library, including simpler types such as std::string. This would be due to the nature of the library's design, given its large usage of inheritance and template programming.

因此,尽管struct A类似于POD类型,但是就编译器而言,它包含标准库类型会自动使该类型的POD无效.

So, while struct A would resemble that of a POD type, the fact that it contains that standard library type automatically invalidates it from that category, as far as the compiler is concerned.

我的假设正确吗?

推荐答案

否.您的基本假设是有缺陷的. 标准布局"与模板无关.例如.当且仅当T1T2都具有std::pair<T1, T2>时,std::pair<T1, T2>具有标准布局. std::array<T,N>

No. Your basic assumptions are flawed. "Standard layout" is not related to templates. E.g. std::pair<T1, T2> has standard layout if and only if both T1 and T2 do. Same goes for std::array<T,N>

但是,容器都没有标准布局.他们的分配器的全部目的是拥有先进的内存管理.

However, none of the Containers have standard layout. The whole point of their allocators is to have advanced memory management.

这篇关于持有标准库容器的结构的POD含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆