为什么删除了复制构造函数的结构不是 POD 类型?
Why is a struct with a deleted copy constructor not a POD type?
我们有以下方法来测试我们的结构是否是POD。它总是 returns 真:
bool podTest() {
struct podTest {
int count;
int x[];
};
return std::is_pod<podTest>::value; //Always returns true
}
到目前为止一切顺利。现在我们进行一项更改并删除复制构造函数:
bool podTest() {
struct podTest {
podTest(const podTest&) = delete;
int count;
int x[];
};
return std::is_pod<podTest>::value; //Always returns false
}
这总是 returns 错误。在阅读了 is_pod
的定义后,我仍然在努力理解它违反了什么要求。我错过了什么?
这是使用 gcc 6.1 在 Godbolt 上编译的,-std=c++14
因为仅在 C++14 之后的 POD 类型才允许删除复制构造函数。我假设,您正在以 C++11 模式编译代码。
啊哈!
来自[class]:
A POD struct is a non-union class that is both a trivial class and a standard-layout class
其中一个琐碎的 class 是:
A trivial class is a class that is trivially copyable and has one or more default constructors (12.1), all of which
are either trivial or deleted and at least one of which is not deleted.
但是在[class.copy]中:
If there is
no user-declared constructor for class X
, a non-explicit constructor having no parameters is implicitly declared as defaulted (8.4).
您的podTest
,当您显式删除复制构造函数时,没有默认构造函数。所以它不是一个微不足道的 class,所以它不是一个 POD。如果你加入:
podTest() = default;
然后又变成POD了
我们有以下方法来测试我们的结构是否是POD。它总是 returns 真:
bool podTest() {
struct podTest {
int count;
int x[];
};
return std::is_pod<podTest>::value; //Always returns true
}
到目前为止一切顺利。现在我们进行一项更改并删除复制构造函数:
bool podTest() {
struct podTest {
podTest(const podTest&) = delete;
int count;
int x[];
};
return std::is_pod<podTest>::value; //Always returns false
}
这总是 returns 错误。在阅读了 is_pod
的定义后,我仍然在努力理解它违反了什么要求。我错过了什么?
这是使用 gcc 6.1 在 Godbolt 上编译的,-std=c++14
因为仅在 C++14 之后的 POD 类型才允许删除复制构造函数。我假设,您正在以 C++11 模式编译代码。
啊哈!
来自[class]:
A POD struct is a non-union class that is both a trivial class and a standard-layout class
其中一个琐碎的 class 是:
A trivial class is a class that is trivially copyable and has one or more default constructors (12.1), all of which are either trivial or deleted and at least one of which is not deleted.
但是在[class.copy]中:
If there is no user-declared constructor for class
X
, a non-explicit constructor having no parameters is implicitly declared as defaulted (8.4).
您的podTest
,当您显式删除复制构造函数时,没有默认构造函数。所以它不是一个微不足道的 class,所以它不是一个 POD。如果你加入:
podTest() = default;
然后又变成POD了