c ++ 11普通旧对象的默认值

Ale*_*ato 4 c++ initialization c++11

如何在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
Run Code Online (Sandbox Code Playgroud)

Seb*_*edl 9

您可以在初始化整个对象的位置执行此操作.一个普通的旧数据对象就是:普通的旧数据,没有不变量,初始化或任何那些花哨的东西.如果你想要初始化,那么它不是POD.

但也许你实际上并不需要POD.也许平凡的可复制就足够了?如果您想要做的就是在对象之间进行memcpy,那么平凡的可复制性就是您正在寻找的特性,而不是POD.