C++ Memory Library - make_shared



Description

It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.

Declaration

Following is the declaration for std::make_shared.

template <class T, class... Args>
   shared_ptr<T> make_shared (Args&&... args);

C++11

template <class T, class... Args>
   shared_ptr<T> make_shared (Args&&... args);

Parameters

args − It is a list of zero or more types.

Return Value

It returns a shared_ptr object.

Exceptions

noexcep − It doesn't throw any exceptions.

Example

In below example explains about std::minus.

#include <iostream>
#include <memory>

int main () {

   std::shared_ptr<int> foo = std::make_shared<int> (100);
   std::shared_ptr<int> foo2 (new int(100));

   auto bar = std::make_shared<int> (200);

   auto baz = std::make_shared<std::pair<int,int>> (300,400);

   std::cout << "*foo: " << *foo << '\n';
   std::cout << "*bar: " << *bar << '\n';
   std::cout << "*baz: " << baz->first << ' ' << baz->second << '\n';

   return 0;
}

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

*foo: 100
*bar: 200
*baz: 300 400
memory.htm
Advertisements