title: Using smart pointers for class members
body: <p>I'm having trouble understanding the usage of smart pointers as class members in C++11. I have read a lot about smart pointers and I think I do understand how <code>unique_ptr</code> and <code>shared_ptr</code>/<code>weak_ptr</code> work in general. What I don't understand is the real usage. It seems like everybody recommends using <code>unique_ptr</code> as the way to go almost all the time. But how would I implement something like this:</p>
  
  <pre><code>class Device {
  };
  
  class Settings {
      Device *device;
  public:
      Settings(Device *device) {
          this-&gt;device = device;
      }
  
      Device *getDevice() {
          return device;
      }
  };    
  
  int main() {
      Device *device = new Device();
      Settings settings(device);
      // ...
      Device *myDevice = settings.getDevice();
      // do something with myDevice...
  }
  </code></pre>
  
  <p>Let's say I would like to replace the pointers with smart pointers. A <code>unique_ptr</code> would not work because of <code>getDevice()</code>, right? So that's the time when I use <code>shared_ptr</code> and <code>weak_ptr</code>? No way of  using <code>unique_ptr</code>? Seems to me like for most cases <code>shared_ptr</code> makes more sense unless I'm using a pointer in a really small scope?</p>
  
  <pre><code>class Device {
  };
  
  class Settings {
      std::shared_ptr&lt;Device&gt; device;
  public:
      Settings(std::shared_ptr&lt;Device&gt; device) {
          this-&gt;device = device;
      }
  
      std::weak_ptr&lt;Device&gt; getDevice() {
          return device;
      }
  };
  
  int main() {
      std::shared_ptr&lt;Device&gt; device(new Device());
      Settings settings(device);
      // ...
      std::weak_ptr&lt;Device&gt; myDevice = settings.getDevice();
      // do something with myDevice...
  }
  </code></pre>
  
  <p>Is that the way to go? Thanks very much!</p>