Irfy
Irfy

Reputation: 9587

Is std::string's default constructor no-throw?

Can std::string s; throw under any circumstances? Is this regulated by the standard (interested in C++03, in case there are differences)?

Upvotes: 5

Views: 3867

Answers (3)

FrankHB
FrankHB

Reputation: 2495

This was changed by WG21/N4002. The first working paper contains it I see is WG21/N4296: // 21.4.2, construct/copy/destroy: basic_string() noexcept : basic_string(Allocator()) { }

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477160

In C++11, the default constructor actually takes one (defaulted) argument, namely the allocator (21.4.2):

explicit basic_string(const Allocator& a = Allocator());

This constructor is not declared as noexcept. (I suppose that would require the allocator to have a non-throwing copy constructor.) As Jonathan and Bo point out, the allocator's copy constructor must not throw any exceptions, but the string's constructor is allowed to perform throwing operations (e.g. allocate an initial piece of memory). It should certainly be possible to write a string-like class that as a no-throw­ing, constexpr constructor, but the standard library string is not specified to be like that.

Upvotes: 5

dchhetri
dchhetri

Reputation: 7136

Sure if allocation isn't possible for any reason it would throw

Upvotes: -2

Related Questions