12.1.3. Using shared_ptrs with new

As we’ve seen, if we do not initialize a smart pointer, it is initialized as a null pointer. As described in Table 12.3, we can also initialize a smart pointer from a pointer returned by new:

shared_ptr<double> p1; // shared_ptr that can point at a doubleshared_ptr<int> p2(new int(42)); // p2 points to an int with value 42

Table 12.3. Other Ways to Define and Change shared_ptrs

Image

The smart pointer constructors that take pointers are explicit7.5.4, p. 296). Hence, we cannot implicitly convert a built-in pointer to a smart pointer; we must use the direct form of initialization (§ 3.2.1, p. 84) to initialize ...

Get C++ Primer, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.