fork download
  1. #include <memory>
  2.  
  3. struct Foo {};
  4. class Bar {
  5. public:
  6. std::unique_ptr<Foo> m_f1; // we will own this
  7. std::unique_ptr<Foo> m_f2; // and this
  8.  
  9. Bar(std::unique_ptr<Foo> f1) // caller must pass ownership
  10. : m_f1(std::move(f1)) // assume ownership
  11. , m_f2(std::make_unique<Foo>()) // create a new object
  12. {}
  13.  
  14. ~Bar()
  15. {
  16. // nothing to do here
  17. }
  18. };
  19.  
  20. int main() {
  21. auto f = std::make_unique<Foo>();
  22. Bar(std::move(f)); // the 'move' emphasizes that
  23. // we're giving you ownership
  24. // 'f' is now invalid.
  25.  
  26. return 0;
  27. }
  28.  
Success #stdin #stdout 0s 3452KB
stdin
Standard input is empty
stdout
Standard output is empty