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


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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.