I'm completing an exercise where I have to make an alternative to the copy-constructor using new and delete. Following the instructions, I end up with this code:
class X {
X(const X&);
public:
int z;
X(int x = 5) : z(x) {}
X clone() const;
};
X X::clone() const {
X* n = new X;
n->z = z;
return *n;
}
X copy(const X& old){
X copy = old.clone();
copy.z++;
return copy;
}
int main(){}
From what I've learned, I expected this to bypass the copy-constructor; however, on lines 16 and 18, it gives me errors referencing line 2 saying the copy-constructor is private. What am I doing wrong?
Hm. Well, the point of the exercise is to disable the copy-constructor by making it inaccessible. Is there any way to not call it and use the clone() function I've written?
Is there any way to not call it and use the clone() function I've written?
I guess. Just don't create object copies.
This includes:
1) don't pass objects by value
2) don't return objects from functions
Both of the above can call the copy ctor.
Also note that your clone funciton is a giant memory leak. You're actually creating two copies:
- One object is created with "new"
- A copy of the "new" object is created and returned from the function
- The "new'd" pointer goes out of scope. Since it was never deleted, memory for it is never freed. Therefore every call to "clone" leaks memory.
Basically this code is really inefficient and sucks up memory. So this approach is illadvised.
Oh wow, thanks for the tip. I didn't realize it was creating two copies.
It's for an exercise to demonstrate how it could be done without the copy-ctor. I know I'm never gonna have to do it like this, but I like to complete all the exercises.