下面的构造函数被认为是微不足道的吗?
struct A
{
A() : a(nullptr) {}
private:
int* a;
};
这些 examples让我有点困惑。对于 c++11,这也应该是可能的:
struct A
{
private:
int* a{nullptr};
};
和a
应该正确初始化为nullptr
。这里我没有定义构造函数,但是应该和第一个实现形式一样。这些类(class)中的任何一个都被认为是微不足道的吗?
我问的目的是我是否可以期望自动生成移动/复制构造函数和赋值运算符。
最佳答案
Is the following constructor considered trivial?
A() : a(nullptr) {}
不是,因为它是用户定义的。
struct A
{
private:
int* a{nullptr};
};
不,因为它有一个非静态成员的大括号初始值设定项。
根据标准(强调我的):
12.1 Constructors
....A default constructor for a class
X
is a constructor of classX
that can be called without an argument. If there is no user-declared constructor for classX
, a constructor having no parameters is implicitly declared as defaulted (8.40).
....A default constructor is trivial if it is not user-provided and if:
....
— no non-static data member of its class has a brace-or-equal-initializer, and
....Otherwise, the default constructor is non-trivial.
The purpose of me asking is if I can expect move/copy constructors and assignment operators being automatically generated.
正如 @M.M 和 @NicolBolas 评论的那样,这些构造函数和运算符的生成不受平凡构造函数存在的影响。
规则有点复杂,不太一致。
复制构造函数只有在没有明确声明的情况下才会生成。 (如果声明了移动构造函数或移动赋值运算符,它会被删除。)
类似地,复制赋值运算符只有在没有明确声明的情况下才会生成。 (同样,如果声明了移动构造函数或移动赋值运算符,它会被删除。)
仅当没有显式声明的移动构造函数、移动运算符、复制构造函数、复制赋值和析构函数时,才会生成移动构造函数。
同样的规则也适用于移动赋值运算符。
关于c++ - 带有初始化列表的空构造函数是否被认为是微不足道的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111510/