2

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?

goodman
  • 424
  • 8
  • 24
  • 2
    https://stackoverflow.com/questions/10315041/meaning-of-acronym-sso-in-the-context-of-stdstring – 康桓瑋 Jan 06 '23 at 07:03
  • 3
    Short string optimization (SSO). Strings below a certain length are stored directly in the string object rather than by allocating memory. Didn't used to be a thing, but now it seems most implementations do it. – john Jan 06 '23 at 07:10
  • @john thanks for the info.Is there any way to avoid the SSO.I want an exception should be thrown if the containers are not initalised with the resource? – goodman Jan 06 '23 at 08:15
  • 1
    If you want to avoid SSO completely, you can use a std::basic_string object with a character type other than char and a character traits type that does not have the SSO optimization enabled – jdenozi Jan 06 '23 at 08:29

0 Answers0