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<T> 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<T> 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 <iostream>
#include <memory>
void result(const std::shared_ptr<int>& i){
(*i)++;
}
int main(){
std::allocator <int> alloc;
std::default_delete <int> del;
auto value = std::allocate_shared<int>(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 <iostream>
#include <memory>
int main (){
std::allocator<int> alloc;
std::default_delete<int> del;
std::shared_ptr<int> Result1 = std::allocate_shared<int> (alloc,11);
auto Result2 = std::allocate_shared<int> (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 <iostream>
#include <memory>
int main (){
std::allocator<int> alloc;
std::default_delete<int> del;
std::shared_ptr<int> Result = std::allocate_shared<int> (alloc);
std::cout << "*Result: " << *Result << '\n';
return 0;
}
Output
when the code gets executed, it will generate the output as shown below −
*Result: 0