~ubuntu-branches/ubuntu/trusty/c++-annotations/trusty

« back to all changes in this revision

Viewing changes to yo/stl/makeshared.yo

  • Committer: Package Import Robot
  • Author(s): Frank B. Brokken
  • Date: 2012-06-28 20:51:43 UTC
  • mfrom: (1.1.21)
  • Revision ID: package-import@ubuntu.com-20120628205143-ykeb4gph8bxuuagl
Tags: 9.4.0-1
New upstream release adds new section about std::make_shared

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
Usually a tt(shared_ptr) is initialized at definition time 
 
2
with a pointer to a newly allocated object. Here is an example:
 
3
        verb(
 
4
    std::shared_ptr<string> sptr(new std::string("hello world"))
 
5
        )
 
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. 
 
9
 
 
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:
 
14
        verb(
 
15
    template<class Type, class ...Args>
 
16
    std::shared_ptr<Type> std::make_shared(Args ...args);
 
17
        )
 
18
    Before using tt(make_shared) the tthi(memory) header file must have
 
19
been included.
 
20
 
 
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.
 
25
 
 
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:
 
29
        verb(
 
30
    auto sptr(std::make_shared<std::string>("hello world"));
 
31
        )
 
32
    After this initialization tt(std::shared_ptr<std::string> sptr) has been
 
33
defined and initialized. It could be used as follows:
 
34
        verb(
 
35
    std::cout << *sptr << '\n';
 
36
        )
 
37