Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a copy of "this" (current instance) in C++

I want to have a copy of the currently running instance.

When i change a value in the copy, original object is also affected. The copy acts as an instance.

How to avoid this? I need to create an independent copy of the calling object.

 Set operator+(Set s){
             Set temp = *this;  

             for(int i=0; s.elements[i] != '\0'; i++){
                     temp(s.elements[i]);
             }
             temp.elements[0] = 'X'; // <- this affects calling object also :(

             return temp;

         }
like image 707
coder9 Avatar asked Oct 20 '10 07:10

coder9


4 Answers

The problem is that Set temp = *this; makes a shallow copy, not a deep copy. You will have to modify the copy constructor and assignment operators for the Set class so that they make copies of all the member/contained objects.

E.g:

class Set
{
public:
    Set()
    {
        elements = new SomeOtherObject[12];
        // Could make elements a std::vector<SomeOtherObject>, instead
    }

    Set(const Set& other)
    {
        AssignFrom(other);
    }

    Set& operator=(const Set& other)
    {
        AssignFrom(other);
        return *this;
    }

private:
    void AssignFrom(const Set& other)
    {
        // Make copies of entire array here, as deep as you need to.
        // You could simply do a top-level deep copy, if you control all the
        // other objects, and make them do top-level deep copies, as well
    }

    SomeOtherObject* elements;
};
like image 175
Merlyn Morgan-Graham Avatar answered Oct 06 '22 17:10

Merlyn Morgan-Graham


Not that your function already makes two copies, since it takes its argument and returns its result per copy:

Set operator+(Set s);

So you wouldn't have to copy s, because it's already copied. I suppose this is involuntarily, so you might want to read about how to pass objects to functions and how to return objects from function in C++.

The problem you're reporting, though, hints at your copy constructor not working properly. Did you implement the copy constructor or are you using the compiler-supplied one?

like image 39
sbi Avatar answered Oct 06 '22 18:10

sbi


This probably depends on how Set is implemented. If the assignment operator and the copy constructor haven't been overloaded to do a deep copy(including elements) then it won't work as expected.

like image 45
CodesInChaos Avatar answered Oct 06 '22 17:10

CodesInChaos


Have you implemented a copy constructor for your class? Default copy constructor will copy any pointer in your class, but not the content you are pointing to. You need to create a copy constructor or overload the '=' operator.

like image 45
Benoit Thiery Avatar answered Oct 06 '22 16:10

Benoit Thiery