Does std::make_shared() use custom allocators?

前端 未结 2 1752
情书的邮戳
情书的邮戳 2021-02-07 04:19

Consider this code:

#include 
#include 


class SomeClass {
public:
    SomeClass() {
        std::cout << \"SomeClass()\" &l         


        
相关标签:
2条回答
  • 2021-02-07 04:37

    Yes, this is standard behavior. From the standard (§20.7.2.2.6 shared_ptr creation ):

    Effects: Allocates memory suitable for an object of type T and constructs an object in that memory via the placement new expression ::new (pv) T(std::forward<Args>(args)...).

    This allows make_shared to allocate the storage for both the object and the data structure for the shared pointer itself (the "control block") in a single allocation, for efficiency reasons.

    You could use std::allocate_shared if you want to control that storage allocation.

    0 讨论(0)
  • 2021-02-07 04:46

    To expand on Mat's correct answer, make_shared is typically implemented by allocating an object that contains the shared_ptr reference counts and a buffer of uninitialized bytes:

    template<typename T>
      struct shared_count_inplace
      {
        long m_count;
        long weak_count;
        typename std::aligned_storage<sizeof(T)>::type m_storage;
        // ...
      };
    

    This is the type which will be allocated on the heap, not your type, so your type's new is not called. Then your type will be constructed using placement new at the location (void*)&m_storage.

    0 讨论(0)
提交回复
热议问题