jgreen81
jgreen81

Reputation: 787

Guarantees on C++ std::string heap memory allocation?

My primary goal is to avoid dynamic memory allocation.

For example, can I be sure which std::string methods will / will not allocate new heap memory?

Is there a way to disallow new allocations by a std::string instance?

Is there a standard fixed length string class?

Upvotes: 2

Views: 1142

Answers (2)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

Is there a way to disallow new allocations by a std::string instance?

No, but instead we can use std::pmr::string since c++17 (If the string is guaranteed to be small enough: say shorter than 16bytes, we may benefit from the std::string's short string optimization in recent version STLS then memory allocation would not happen, but it's a black-box)

constexpr size_t kMaxLen = 256;
char buffer[kMaxLen] = {};
std::pmr::monotonic_buffer_resource pool{std::data(buffer),std::size(buffer)};
std::pmr::string vec{&pool};

// assert that we don't have a string with a length larger than kMaxLen - 1, or we will trigger heap memory allocations

Is there a standard fixed-length string class?

NO, but we may choose non standard libraries as the alternatives:

Upvotes: 1

eerorika
eerorika

Reputation: 238301

For example, can I be sure which std::string methods will / will not allocate new heap memory?

No, the standard doesn't guaratee non-allocation.

However, you can provide a user defined allocator to std::basic_string. If you don't use dynamic allocation in your custom allocator, then there will be no dynamic allocation.

Is there a standard fixed length string class?

No.

Upvotes: 2

Related Questions