Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL swap on return?

sorry for such a long question but I try to be as clear as possible. This somehow follows my previous question about strings in C++. I'm trying to figure out how I could return std::string from a function without redundant memory allocations, without relying on NRVO. The reasons why I don't want to rely on NRVO are:

  • it is not supported by the compiler we currently use
  • even when it is supported it might not always be enabled in Debug mode
  • it might fail in some cases (example)

Please note that I need a C++03 compatible solution (no C++0x rvalue references thus, unfortunately...)

The simplest way do this is pass-by-reference and do std::swap, like this

void test(std::string& res)
{
    std::string s;
    //...
    res.swap(s);
}

But it is more natural and often more convenient to return by value than pass by reference, so what I want to achieve is this:

std::string test()
{
    std::string s;
    //...
    return SOMETHING(s);
}

Ideally it would just do a swap with the "return value", but I don't see how to do this in C++. There is auto_ptr already which does move instead of copy, and I could actually use auto_ptr<string>, but I'd like to avoid dynamically allocating the string object itself.

My idea is to somehow "tag" a string object that it is being returned from a function to permit moving its data when a copy constructor is called on return. So I ended up with this code, which does exactly what I want:

struct Str
{
    struct Moveable
    {
        Str & ref;
        explicit Moveable(Str & other): ref(other) {}
    };

    Str() {}
    Str(const std::string& other) : data(other) {} // copy
    Str(Moveable& other) { data.swap(other.ref.data); } // move

    Moveable Move()
    {
        return Moveable(*this);
    }

    std::string data;
};

Str test()
{
    Str s;
    //...
    return s.Move(); // no allocation, even without NRVO
}

So... Does all this make sense, or there are some serious issues that I'm missing? (I'm not sure if there is no lifetime issue for example). Maybe you have already seen such idea in a library (book, article...), and could give me a reference to it?

EDIT: As @rstevens noticed, this code is MSVC-specific and won't compile under g++ which does not like the non-const temporary. This is an issue, but let's just assume this implementation is MSVC-specific.

like image 243
Roman L Avatar asked Jan 19 '11 17:01

Roman L


Video Answer


1 Answers

The implementation of boost uses move semantics emulation internally for libraries like Boost.Thread. You may want to look at the implementation and do something similar.

Edit: there is actually an active development of a library Boost.Move, so you can already start using it.

like image 69
Yakov Galka Avatar answered Sep 27 '22 23:09

Yakov Galka