Chapter 29. Using auto_ptr

Difficulty: 5

This Item illustrates a common pitfall with using auto_ ptr. What is the problem, and how can you solve it?

  1. Consider the following function, which illustrates a common mistake when using auto_ptr:

    template<typename T>
    void f( size_t n ) {
      auto_ptr<T> p1( new T );
      auto_ptr<T> p2( new T[n] );
    
      // ... more processing ...
    }
    

    What is wrong with this code? Explain.

  2. How would you fix the problem? Consider as many options as possible, including the Adapter pattern, alternatives to the problematic construct, and alternatives to auto_ptr.

Solution

Solution

Problem: Arrays and auto_ptr Don't Mix

  • 1. Consider the following function, which ...

Get More Exceptional C++ 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.