lundi 28 décembre 2020

Move operator destroying original pointer

I am trying to have a pointer to a memory location. Then, if I modify the original the assigned variable who points to the same location must be also affected by the change.

But, the thing is, there are two function calls, that happen on line:

a = Data("New data");
  1. Data(const char* cdata) constructor is called.
  2. Data operator=(Data&& data) move operator is called.

My C++ code:

class Data 
{
private:
    char* local_data;
    int _size = 0;
public:
    Data() {
        local_data = new char[_size];
    }
    
    Data(const char* cdata){
        local_data = new char[_size];
        memcpy(local_data, cdata, _size);
    }
    
    int size() { return _size; }
    char* data() { return local_data; }
    const char* data() const { return local_data; }
    
    Data& operator=(const Data& data){}
    Data& operator=(Data&& data){
        
        if(this == &data)
            return *this;
        
        _size = std::move(data.size());
        local_data = std::move(data.data());
        return *this;
    }
};

int main(){
    
    Data a("Some data");
    auto dptr = a.data(); // Gives a pointer to the original location
    a = Data("New data"); // Must modify both a and dptr
    assert(dptr == a.data()); // Should pass successfully, else fail
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire