如何在 C++11 中初始化 POD(普通旧数据)的成员变量?
class A {
public:
int theAnswer; // this is not initialized
};
static_assert(std::is_pod<A>::value, "A must be a plain old object");
class B {
public:
int theAnswer { 42 }; // this should initialize to 42
};
static_assert(std::is_pod<B>::value, "B must be a plain old object"); // ERROR
class C {
public:
C() : theAnswer { 42 } { } // Obviously, this is not a trivial default constructor, so it does not work
int theAnswer;
};
static_assert(std::is_pod<C>::value, "C must be a plain old object"); // ERROR
最佳答案
您在初始化整个对象的地方执行此操作。一个普通的旧数据对象就是:普通的旧数据,没有不变量、初始化或任何花哨的东西。如果要初始化,那就不是POD了。
但也许您实际上并不需要 POD。也许平凡可复制就足够了?如果您想做的只是对象之间的 memcpy,那么您正在寻找的特征是简单可复制,而不是 POD。
关于C++11 普通旧对象默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754024/