1
Usually a tt(shared_ptr) is initialized at definition time
2
with a pointer to a newly allocated object. Here is an example:
4
std::shared_ptr<string> sptr(new std::string("hello world"))
6
In such statements em(two) memory allocation calls are used: one for the
7
allocation of the tt(std::string) and one used interally by
8
tt(std::shared_ptr)'s constructor itself.
10
The two allocations can be combined into one single allocation (which is
11
also slightly more efficient than explicitly calling tt(shared_ptr)'s
12
constructor) using the ti(make_shared) template. The function template
13
tt(std::make_shared) has the following prototype:
15
template<class Type, class ...Args>
16
std::shared_ptr<Type> std::make_shared(Args ...args);
18
Before using tt(make_shared) the tthi(memory) header file must have
21
This function template allocates an object of class tt(Type), passing
22
tt(args) to its constructor (using em(perfect forwarding), see section
23
ref(PERFECT)), and returns a tt(shared_ptr) initialized with the address of
24
the newly allocated tt(Type) object.
26
Here is how the above tt(sptr) object can be initialized
27
using tt(std::make_shared). Notice the use of tt(auto) which frees us from
28
having to specify tt(sptr)'s type explicitly:
30
auto sptr(std::make_shared<std::string>("hello world"));
32
After this initialization tt(std::shared_ptr<std::string> sptr) has been
33
defined and initialized. It could be used as follows:
35
std::cout << *sptr << '\n';