Krishna_Oza Krishna_Oza - 2 months ago 12
C++ Question

Heap objects don’t naturally support copy semantics

What is the meaning of Heap objects don’t naturally support copy semantics in C++. I found this while reading the CPP FAQ https://isocpp.org/wiki/faq/csharp-java#universal-object but could not understand the meaning and applicability to C++.

Answer
int a = 10;
int b = a;

In this above case, the value of a is copied to b. But consider,

int* c = new int(10);
int* d = c;

In this case, data is not copied but both the pointers point to same address.
If you delete c, then d points to invalid memory. In order to avoid this, you need to allocate memory for d separately and then copy the data.

int* c = new int(10);
int* d = new int(*c);

When you have a class that has pointers, then you should make sure you define
copy-constructor and assignment operator and then handle the copy of data similar to the way I showed below.

For eg.,

class A
{
    private:
     int* m_data;

    public:

      A() : m_data(NULL) { }
      A(int x) : m_data(new int(x)) { }
      ~A() { delete m_data; }

      // Failing to provide the below 2 functions will 
      // result in shallow copy of pointers 
      // and results in double delete of pointers.
      A(const A& other) : m_data(new int(*(other.m_data)) { }
      A& operator=(const A& other)
      {
           A temp (other);
            std::swap (m_data, temp.m_data);
           return *this;
      }
};