gpt4 book ai didi

c++ - 即使使用用户定义的构造函数,编译器何时仍会生成默认构造函数?

转载 作者:太空狗 更新时间:2023-10-29 20:59:57 24 4
gpt4 key购买 nike

在《C++ Concurrency in Action》附录A.3中,在介绍默认函数时,它说:

Under normal circumstances, if you write any other constructor manually, the compiler will no longer generate the default constructor for you, so if you want one you have to write it, which means you lose this bizarre initialization property. However, by explicitly declaring the constructor as defaulted, you can force the compiler to generate the default constructor for you, and this property is retained.

这是否意味着在某些情况下(除了显式添加 =default )编译器仍然会生成默认构造函数,即使是用户定义的构造函数?如果是,这些情况是什么?或者只是我对这里的措辞吹毛求疵。

最佳答案

这是由 C++11 12.1/5 回答的:

If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted.

因此,只要您声明了任何其他构造函数(即使是默认构造函数或已删除构造函数),就不会隐式声明默认构造函数。

例子:

#include <type_traits>

struct A { };

struct B { B(B &&) = delete; };

static_assert(std::is_default_constructible<A>::value, "A");
static_assert(!std::is_default_constructible<B>::value, "B");

关于c++ - 即使使用用户定义的构造函数,编译器何时仍会生成默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23383186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com