Beispiel : MyRes Klasse

Einfache Klasse die mit new dynamisch Speicher anlegt \bgroup\color{green}\ensuremath{\Rightarrow}\egroup Management dieser Resource erforderlich.
Nur zur Illustration, in modernem C++ eigentlich kein memory management mit new/delete.


// C++ class allocating resource
//
// example adapted from:
// https://www.geeksforgeeks.org/move-constructors-in-c-with-examples/
//
#include <iostream>
#include <vector>
using namespace std;

// MyRes Class
class MyRes {
private:
  // Declaring the raw pointer as
  // the data member of the class
  int* data;
  
public:
  // Constructor with int
  MyRes(int d)
  {
    // Declare object in the heap
    data = new int;
    *data = d;
    cout << "Constructor is called for " << d << endl;
  };
  // Copy Constructor 
  MyRes(const MyRes& source)
    : MyRes{ *source.data }
  { 
    // Copy constructor copying
    // the data by making deep copy
    cout << "Copy Constructor is called - "
     << "Deep copy for " << *source.data << endl;
  }
  // assignment operator
  MyRes & operator = (const MyRes & source)
  {
    cout << "= operator is called for " << *source.data << endl;
    if (data != nullptr) { // clean up existing data 
      cout << "= operator clean up old data " << *data << endl;
      // Free the memory assigned to data member of the object
      delete data;
    }
    // Declare object in the heap
    data = new int;
    *data = *source.data;
    return *this;
  }
  // Destructor
  ~MyRes()
  {
    if (data != nullptr) { // If the pointer is not pointing to nullptr
      cout << "Destructor is called for " << *data << endl;
      //
      // Free the memory assigned to data member of the object
      delete data;
    }
    else {// If the pointer is pointing to nullptr
      cout << "Destructor is called" << " for nullptr"  << endl;
    }
  }
};
 
// Driver Code
int main()
{
  // Create vector of MyRes Class
  vector<MyRes> vec;
  
  // Inserting object of MyRes class
  vec.push_back(MyRes{ 10 });
  cout << "vector filled 10 " << endl;
  vec.push_back(MyRes{ 20 });
  cout << "vector filled 20" << endl;
  
  // overwrite existing element
  vec[1] = MyRes{30};
  
  return 0;
}


In modernem C++ geht es noch weiter, es sind eigentlich noch move constructor sowie move assignment operator nötig...
\bgroup\color{green}\ensuremath{\Rightarrow}\egroup Stoff für advanced C++.