0

I am new to C++ and encountered a problem that I did not understand.

I intended to use a custom cctor dCopy(int) to create an instance A and use a copy cctor dCopy(const dCopy&) to create a deep copy of A.

Here is the code:

#include <iostream>

using std::cout;
using std::endl;

class dCopy {
    public:
    int *a;

    dCopy(int);
    dCopy(const dCopy &);
    ~dCopy();
};

// implementation
dCopy::dCopy(int b) {
    a = new int(b);
}

dCopy::dCopy(const dCopy & other) {

    dCopy(*other.a);
}

dCopy::~dCopy() {
    delete a;
    a = nullptr;

    cout << "It seems that there is no memory leakage." << endl;
}

//main
int main() {
    dCopy A(1);
    dCopy B(A);
}

The entire code cause the error of "pointer being freed was not allocated."

The issue I found is the implementation of dCopy(const dCopy & other)

If I directly call the custom cctor will cause the error.

dCopy::dCopy(const dCopy & other) {

    dCopy(*other.a);
}

However, If I write in this way the error was gone.

dCopy::dCopy(const dCopy & other) {

    a = new int(*other.a)
}

However, from my understanding, calling dCopy(*other.a) is the same with a = new int(*other.a) but I am not so sure.

Is it because the right implementation created a new instance of a?

JoeeeeX
  • 11
  • 2
    You aren't delegating to another c'tor, you are creating a temporary class object and immediately discarding it. Refer to the linked question for the correct way to do this in C++. – StoryTeller - Unslander Monica Aug 19 '23 at 08:27
  • @JoeeeeX This talk from 2019 covers everything you need to know: [Back to Basics: RAII and the Rule of Zero - Arthur O'Dwyer - CppCon 2019](https://www.youtube.com/watch?v=7Qgd9B1KuMQ) – tbxfreeware Aug 19 '23 at 09:39
  • 2
    @JoeeeeX Try `dCopy::dCopy(const dCopy& other) { a = other.a == nullptr ? nullptr : new int(*other.a); }` In general, if you define a dtor and copy-ctor, you also need to define a copy-assignment `operator=`, and this is not an exception. That's the so-called _Rule of Three_. If you toss in a move-ctor and move-assignment (which are not needed here), you get the _Rule of Five_. – tbxfreeware Aug 19 '23 at 10:07
  • @tbxfreeware Thank you so much for the video link and the solution! – JoeeeeX Aug 19 '23 at 16:09
  • @StoryTeller-UnslanderMonica Oh, I see! I am learning delegating constructors now!!! Thank you ! – JoeeeeX Aug 19 '23 at 16:10

0 Answers0