Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the default constructor of std::list<int> throw?

I had a (quick) look into the C++ standard and into an online C++ reference, but I could not find an answer to this simple question:

Can the default constructor of std::list<int> throw?

If so, why would it throw?

like image 887
Ralph Tandetzky Avatar asked Nov 12 '13 13:11

Ralph Tandetzky


People also ask

Does the default constructor get called?

A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter). A type with a public default constructor is DefaultConstructible.

Is default constructor created automatically?

The default constructor is auto-generated if there is no user-declared constructor (§12.1/5).

Does copy constructor call default constructor?

The answer is No. The creation of the object memory is done via the new instruction. Copy constructor is then in charge of the actual copying (relevant only when it's not a shallow copy, obviously). You can, if you want, explicitly call a different constructor prior to the copy constructor execution.

Does CPP provide a default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


1 Answers

Short answer: it can, but it may be implemented in a way that is reasonably safe:

The default constructor constructs an empty list, so there is little need to actually allocate memory in the process. Most list implementations won't allocate any memory for an empty list.

However, the default constructor is not really a default constructor, since it has a defaulted argument: explicit list(const Allocator& = Allocator());
Allocator itself is a template argument, so the call of the constructor already might throw, if Allocator has a sufficiently dumb (or complex) implementation providing a throwing default constructor, i.e. if the construction of the default argument throws.

If the default constructor of Allocator does not throw, it is realtively easy to provide an implementation of std::list whose default constructor won't throw either. But library implementors are not required to do so.

Updated: The list has to store a copy of the given allocator to be able to call it later. Contrary to my prior claim, the resulting call to the copy constructor of Allocator may not throw (§17.6.3.5, see the comments). The list implementation is also not allowed to e.g. default-construct the allocator and do a copy assignment in the constructor, because that would break any code that tries to use the list with allocators that are not default-constructible.

like image 140
Arne Mertz Avatar answered Sep 26 '22 11:09

Arne Mertz