vendredi 28 juillet 2017

Why move semantics has the same behavior as shallow copy in dynamic mem allocation?

In the classes dealing with dynamic mem allocation, shallow copy basically causes the program to delete a resource twice. In move operations, the original pointer no longer points to the resource, So But why the same behavior occurs in move semantics? e.g:

#include <utility>
#include <cstring>
using namespace std;
class MyString
{
    char* cstr;
 public:
    MyString(const char* arg)
    : cstr(new char[strlen(arg)+1])
    {
        strcpy(cstr, arg);
    }
    MyString(MyString&&) = default;
    MyString& operator=(MyString&&) = default;
    MyString(const MyString&) = delete;
    MyString& operator=(const MyString&) = delete;
    ~MyString()
    {
        delete[] cstr;
    }
};

int main()
{
    MyString S1{"aaa"};
    MyString S2 = move(S1); // error

}

I've tried with 3 different compilers and i got the same results.

Aucun commentaire:

Enregistrer un commentaire