我知道除其他外,必须隐式定义一个普通的构造函数。
当我们使用 default 关键字时,这是否也适用?
假设我们指定了一个 T()=default constructor ,它是被认为是用户提供的还是被视为一个隐式构造函数?
最佳答案
是的,在第一次声明时默认的用户声明的构造函数可能是微不足道的:
struct Foo
{
Foo() = default;
Foo(int, int);
char x;
};
#include <type_traits>
static_assert(std::is_trivially_constructible<Foo>::value, "Works");
该示例演示了如何在存在用户定义(非默认)构造函数的情况下定义 POD 类。
根据标准 (12.1),“如果不是用户提供的默认构造函数是微不足道的”(加上条件),以及 (8.4.2):
A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.
但是,请注意,默认构造函数的琐碎性不仅仅取决于它的声明和定义。扩展 12.1 中的引用:
A default constructor is trivial if it is not user-provided and if:
— its class has no virtual functions (10.3) and no virtual base classes (10.1), and
— no non-static data member of its class has a brace-or-equal-initializer, and
— all the direct base classes of its class have trivial default constructors, and
— for all the non-static data members of its class that are of class type (or array thereof), each such class has a trivial default constructor.
关于c++ - 使用 default 关键字指定的构造函数是否微不足道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23007358/