如果类 S 是一个聚合或者至少具有一个普通的合格构造函数和一个普通的、未删除的析构函数,则它是隐式生命周期类。
并且可以使用 malloc 创建隐式生命周期对象。请参阅此示例。
#include <cstdlib>
struct X { int a, b; };
X* MakeX()
{
// One of possible defined behaviors:
// the call to std::malloc implicitly creates an object of type X
// and its subobjects a and b, and returns a pointer to that X object
X* p = static_cast<X*>(std::malloc(sizeof(X)));
p->a = 1;
p->b = 2;
return p;
}
Run Code Online (Sandbox Code Playgroud)
但struct A {std::string s;};也是一个总和。但这会产生一个异常,正如我所期望的,因为对 s 的赋值将首先破坏 …