Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will compiler still generate the default constructor even with user defined constructors?

In book "C++ Concurrency in Action" Appendix A.3, when introducing defaulted functions, it says:

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.

Does it mean that there still are some circumstances (except for adding =default explicitly) that the compiler will still generate the default constructor even with user defined constructors? If yes, what are these circumstances? Or just I am over nit-picking on words here.

like image 547
herohuyongtao Avatar asked Apr 30 '14 08:04

herohuyongtao


Video Answer


1 Answers

This is answered by 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.

So as soon as you declare any other constructor (even if as defaulted or deleted), there's no implicitly declared default constructor.

Example:

#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");
like image 112
Kerrek SB Avatar answered Nov 02 '22 23:11

Kerrek SB