Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the memory allocation done for vectors declared static

Tags:

c++

I guess my question boils down to: What is the problem std::inplace_vector solves, but here is a bit more details:

I have a std::vector as part of my singleton, which, since it is static, should be allocated static memory at compile time. However since the vector is essentially a dynamic array (it might not be that simple, but the analogy works in this case so give me some leeway), how is the memory allocated? How much memory is allocated at compile time? What happens when I insert more elements to the vector and it needs to resize, considering the static memory is already allocated and limited?

class SingletonClass
{
    public:
        static SingletonClass& getInstance()
        {
            static SingletonClass instance;
            return instance;
        }
    std::vector<int> singletonVector;
};
like image 766
user16883542 Avatar asked Oct 25 '25 14:10

user16883542


1 Answers

my question boils down to: What is the problem std::inplace_vector solves ...

That can be found in p0843r14:

Motivation and Scope

The inplace_vector container is useful when:

  • memory allocation is not possible, e.g., embedded environments without a free store, where only automatic storage and static memory are available;
  • memory allocation imposes an unacceptable performance penalty, e.g., in terms of latency;
  • allocation of objects with complex lifetimes in the static-memory segment is required; the storage location of the inplace_vector elements is required to be within the inplace_vector object itself, e.g., for serialization purposes (e.g. via memcpy);
  • std::array is not an option, e.g., if non-default constructible objects must be stored; or
  • a dynamically-resizable array is needed during constant evaluation.
like image 135
Ted Lyngmo Avatar answered Oct 28 '25 03:10

Ted Lyngmo