If I construct an empty std::vector
using the default constructor (and the default allocator), can it throw an exception?
In general, allocating space for the elements of a container can throw an exception (which would be a std::bad_alloc
). But the default constructor of a std::vector
does not need to allocate any such space; it can lazily allocate some space on the first insertion or assignment. But does the C++ standard require that it does not throw exceptions (implying lazy allocation, or catching std::bad_alloc
and then falling back to lazy allocation)?
Yes, just like methods you can throw exceptions from constructors in.
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.
The default vector constructor takes no arguments, creates a new instance of that vector. The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c. All of these constructors run in linear time except the first, which runs in constant time.
The default constructor of std::vector is declared as And if std::allocator is used then it's noexcept (true); i.e. won't throw exceptions. Hence, before C++17, or if using a non-default allocator, throwing exceptions is possible.
In general, allocating space for the elements of a container can throw an exception (which would be a std::bad_alloc ). But the default constructor of a std::vector does not need to allocate any such space; it can lazily allocate some space on the first insertion or assignment.
The destructors are noexcept by default. (since C++11) Nofail (the function always succeeds) is expected of swaps, move constructors, and other functions used by those that provide strong exception guarantee.
The C++ default constructor std::vector::vector()constructs an empty container, with zero elements. Size of this container is always zero. The storage for container is allocated by internal allocator.
It depends on the default constructor of Allocator
. The default constructor of std::vector
is declared as
vector() noexcept(noexcept(Allocator())); (since C++17)
And if std::allocator
is used then it's noexcept(true)
; i.e. won't throw exceptions.
allocator() noexcept; (since C++11)
Hence, before C++17, or if using a non-default allocator, throwing exceptions is possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With