I am learning about the null_memory_resource
and tried using it in a simple example. I set it as the default memory resource with set_default_resource
and attempted to initialize a std::vector
, but received a std::bad_alloc
exception because the vector was trying to allocate memory using the null_memory_resource
, which does not actually allocate any memory but throws an exception.
Now I am experimenting with a std::string
and found that if the string size is below 16, no exception is thrown, but if the size is above 16, an exception is thrown. Any specific reason for this behavior?
The code snippet:
#include <iostream>
#include <memory_resource>
#include <string>
#include <vector>
#include <unistd.h>
int main()
{
std::pmr::memory_resource* default_resource = std::pmr::null_memory_resource();
std::pmr::set_default_resource(default_resource);
try
{
std::pmr::vector<std::uint8_t> data{1};
}catch(std::bad_alloc e)
{
std::cerr << "bad_alloc is thrown vector" << std::endl;
}
// No exception here if the size is below 16
std::pmr::string str1 {"abcdefghi"};
std::cerr << str1 << " Length:" << str1.size() << std::endl;
try
{
// Exception here if the size is >= 16
std::pmr::string str2 {"abcdefghijklmnop"};
}catch(std::bad_alloc e)
{
std::cerr << "bad_alloc is thrown string" << std::endl;
}
return 0;
}
Output:
bad_alloc is thrown vector
abcdefghi Length:9
bad_alloc is thrown string
online compiler: https://godbolt.org/z/147ceMc7n
Edit1: Thanks for the info about SSO; now I understand the behavior of the program. But is there any way to avoid the SSO completely?