Quick Q: Why have move semantics? -- StackOverflow

Quick A: Because value semantics are clean and naturally (exception-)safe, and avoid the brittleness of pre-C++11 workarounds that resort to owning raw pointers.

As often happens, the question contains the answer...

Why have move semantics?

... Can't the client already take advantage of pointers to do everything move semantics gives us? If so, then what is the purpose of move semantics?

Move semantics:

std::string f()
{
    std::string s("some long string");
    return s;
}
int main()
{
    // super-fast pointer swap!
    std::string a = f();
    return 0;
}

Pointers:

std::string *f()
{
    std::string *s = new std::string("some long string");
    return s;
}

int main()
{
    // still super-fast pointer swap!
    std::string *a = f();
    delete a;
    return 0;
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.