C++ Memory::allocate_shared



C++ Memory::allocate_shared allocates memory for an object of type T using alloc and constructs it passing args to its constructor. Typically, this procedure uses a single memory allocation to allocate memory for the shared ptrs control block as well as the T object (it is a non-binding requirement in the Standard). In comparison, at least two memory allocations are made in the declaration std::shared ptr p(new T(Args...)), which can result in extra overhead.

The control block contains a copy of alloc that can be used to deallocate memory once the shared and weak reference counts are zero.

Syntax

Following is the syntax for C++ Memory::allocate_shared −

shared_ptr allocate_shared (const Alloc& alloc, Args&&... args);

Parameters

  • args − It is an allocator object.
  • alloc − It is a list of zero or more types.

Example 1

Let's look into the following example, where we are using the allocate_shared and retriveing the value.

#include 
#include 
void result(const std::shared_ptr& i){
   (*i)++;
}
int main(){
   std::allocator  alloc;
   std::default_delete  del;
   auto  value = std::allocate_shared(alloc,10);
   result(value);
   std::cout << *value << std::endl;
}

Output

Let us compile and run the above program, this will produce the following result −

11

Example 2

Following is the another scenario, where we are going to use the allocate_shared and retrieving the value.

#include 
#include 
int main (){
   std::allocator alloc;
   std::default_delete del;
   std::shared_ptr Result1 = std::allocate_shared (alloc,11);
   auto Result2 = std::allocate_shared (alloc,1);
   std::cout << "*Result1: " << *Result1 << '\n';
   std::cout << "*Result2: " << *Result2 << '\n';
   return 0;
}

Output

On running the above code, it will display the output as shown below −

*Result1: 11
*Result2: 1

Example 3

Considering the following where we are not to going to pass any kind of value for the allocate_shared as a result it will return the value '0'.

#include 
#include 
int main (){
   std::allocator alloc;
   std::default_delete del;
   std::shared_ptr Result = std::allocate_shared (alloc);
   std::cout << "*Result: " << *Result << '\n';
   return 0;
}

Output

when the code gets executed, it will generate the output as shown below −

*Result: 0
Advertisements