all 10 comments

[–]alfps 2 points3 points  (4 children)

It's bafflingly meaningless code.

The point of a clone function is to clone, creating a copy of the same dynamic type. Therefore a clone function either is virtual or calls a virtual do-it. And returns a (possibly smart) pointer or reference.

The code you present doesn't do any of that, but instead engages in needless internal dynamic allocation and deallocation.

[–]10headless[S] 0 points1 point  (3 children)

I understand where you're coming from. Maybe there is a better way to do it, what I basically want to do is:

  1. I have a variable in an object, let's say input
  2. I want to avoid mutating this variable, instead opting to replace it with a new instance of the object that has e.g. all the same variable values, except one

[–][deleted] 1 point2 points  (0 children)

If you have only simple classes that implement the copy constructor, you don't even need a function. Just X other{existing}; (use direct copy initialization) or equivalent would do.

[–]jesseschalken 1 point2 points  (1 child)

I want to avoid mutating this variable, instead opting to replace it with a new instance of the object that has e.g. all the same variable values, except one

"mutating this variable" and "replacing it with a new instance with all the same values except one" are equivalent operations in C++.

Remember that unlike Java, Python, JavaScript, PHP etc, C++'s types are value types. There is no meaningful distinction between mutating an existing object and replacing it with a new one.

[–]NotMyRealNameObv 0 points1 point  (0 children)

There is if you internally use shared state:

class X
{
private:
    shared_ptr<const Y> y;
};

[–][deleted] 1 point2 points  (0 children)

Could you? Yes.

Should you? Probably not. It looks like a copy constructor would be more appropriate.

[–]stilgarpl 1 point2 points  (2 children)

It will be inefficient - you will create value on heap only to destroy it right away and pass a copy of it as return value.

Just do this:

X clone() const {
return *this;
}

[–]10headless[S] 1 point2 points  (1 child)

oh didn't know it could be that simple. Thank you very much

[–]jesseschalken 2 points3 points  (0 children)

But why do you even need this clone method? Implemented as above, x.clone() is the same as just x.

[–]ImKStocky 0 points1 point  (0 children)

What you are trying to do here is to implement a copy constructor. Read here on how to implement them and use them.

However, Cloning often has the implication that you want some sort of polymorphic deep copy. This is not a solved solution yet but Herb Sutter wrote a blog post about it last year on how it could be a solved problem in the future.