问题描述
在c ++ 11中,Union支持非POD成员。我想在构造函数中初始化一个非POD成员。
In c++11, Union supports non-POD member. I want to initialize a non-POD member in the constructor.
在wikipedia c ++ 11上,它使用展示位置new初始化非POD成员。
On wikipedia c++11 page, it uses a placement 'new' to initialize a non-POD member.
#include <new> // Required for placement 'new'.
struct Point {
Point() {}
Point(int x, int y): x_(x), y_(y) {}
int x_, y_;
};
union U {
int z;
double w;
Point p; // Illegal in C++03; legal in C++11.
U() {new(&p) Point();} // Due to the Point member, a constructor definition is now required.
};
我想知道如果我使用ctor-initializer-list而不是placement'new' ?
I am wondering is there any difference if I use ctor-initializer-list instead of placement 'new'?
U() : p() {}
推荐答案
您可以在 ctor-initializer-list 中最多一个成员初始化。 union是一个类,所以[class.base.init](C ++ 11§12.6.2)中的成员初始化器的规则适用于具有类键 struct
或 class
。一个明显的例外情况在12.6.2 / 8中说明:试图初始化一个联合的多个非静态数据成员会使程序生成错误。
You are free to initialize at most one member of a union in the ctor-initializer-list. A union is a class, so the rules for member initializers in [class.base.init] (C++11 §12.6.2) apply just as they do to classes with the class-key struct
or class
. One obvious exception is stated in 12.6.2/8: "An attempt to initialize more than one non-static data member of a union renders the program ill-formed."
这篇关于如何在Union中初始化非POD成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!