mardi 29 décembre 2020

What would a proper way to go, to get the "Copy & Swap Idiom" to work here?

MY Previous question:


In the code below, I need the variable auto ptr to remain valid and the assertion to pass.

   auto ptr = a.data();

Looks like this:

   +--------------+
   | a.local_data | --\
   +--------------+    \     +-------------+
                        >--> | "Some data" |
   +-----+             /     +-------------+
   | ptr | -----------/
   +-----+

#include <iostream>
#include <cassert>
using namespace std;

class Data 
{
private:
    char* local_data;
    int _size = 0;
    
    inline int length(const char* str)
    {
        int n = 0;
        while(str[++n] != '\0');
        return n;
    }
    
public:
    Data() {
        local_data = new char[_size];
    }
    
    Data(const char* cdata) : _size { length(cdata) }{
        local_data = new char[_size];
        std::copy(cdata, cdata + _size, local_data);
    }
    
    int size() const { return _size; }
    const char* data() const { return local_data; }
    
    void swap(Data& rhs) noexcept
    {
        std::swap(_size, rhs._size);
        std::swap(local_data, rhs.local_data);
    }
    
    Data& operator=(const Data& data)
    {
        Data tmp(data);
        swap(tmp);
        return *this;
    }
};



int main()
{
    Data a("Some data");
    auto ptr = a.data(); // Obtains a pointer to the original location
    a = Data("New data");
    assert(ptr == a.data()); // Fails
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire