c++ - 使用 default 关键字指定的构造函数是否微不足道?

标签 c++ constructor default

我知道除其他外,必须隐式定义一个普通的构造函数。

当我们使用 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/

相关文章:

c++ - 新 flex-bison 中旧 lex-yacc 代码的兼容性问题

C++ 访问说明符

java - 创建在其外部类的构造函数中使用的类的实例

c++ - 我可以通过重新播种结合 random_device 和 mt19937 生成加密安全随机数据吗?

javascript - new F 和 new F() 有什么不同吗?

java - Kotlin : Passing HashMap with multiple value types into function

java - 如何设置系统默认字体为JComboBox<String>的选中项?

显示传递和默认 kwargs 的 python 装饰器

java - 如何为 WildFly 服务器设置默认错误页面?

c++ - 需要帮助让英特尔 TBB 正常工作吗?