×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Text
Posted by: Massi Massi
Added: Sep 22, 2016 11:00 AM
Views: 3
Tags: no tags
  1.  
  2. class Foo
  3. {
  4.   public:
  5.     /** Default constructor */
  6.     Foo() :
  7.             data (new char[14])
  8.     {
  9.       std::strcpy(data, "Hello, World!");
  10.     }
  11.  
  12.     /** Copy constructor */
  13.     Foo (const Foo& other) :
  14.             data (new char[std::strlen (other.data) + 1])
  15.     {
  16.       std::strcpy(data, other.data);
  17.     }
  18.  
  19.     /** Move constructor */
  20.     Foo (Foo&& other) noexcept : /* noexcept needed to enable optimizations in containers */
  21.             data(other.data)
  22.     {
  23.       other.data = nullptr;
  24.     }
  25.  
  26.     /** Destructor */
  27.     ~Foo() noexcept /* explicitly specified destructors should be annotated noexcept as best-practice */
  28.     {
  29.       delete[] data;
  30.     }
  31.  
  32.     /** Copy assignment operator */
  33.     Foo& operator= (const Foo& other)
  34.     {
  35.       Foo tmp(other);         // re-use copy-constructor
  36.       *this = std::move(tmp); // re-use move-assignment
  37.       return *this;
  38.     }
  39.  
  40.     /** Move assignment operator */
  41.     Foo& operator= (Foo&& other) noexcept
  42.     {
  43.       delete[] data;
  44.       data = other.data;
  45.       other.data = nullptr;
  46.       return *this;
  47.     }
  48.  
  49.   private:
  50.     friend std::ostream& operator<< (std::ostream& os, const Foo& foo)
  51.     {
  52.       os << foo.data;
  53.       return os;
  54.     }
  55.  
  56.     char* data;
  57. };