Home > Net >  move semantics for `this`?
move semantics for `this`?

Time:05-10

Imagine the following situation:

class C {
  public:
  C(std::vector<int> data): data(data) {}
  C sub_structure(std::vector<size_t> indices){
    std::vector<int> result;
    for(auto i : indices)
      result.push_back(data[i]); // ***
    return C(result);
  }
  std::vector<int> data;
};
C f(){
  ...
}
...
C c = f().sub_structure(...);

I guess in the line marked ***, copies of the elements of data are made, altough sub_structure is called on an object that's about to be destroyed.

If my call was something like sub_structure(f(), ...), I could overload sub_structure by rvalue reference; however, as a class method, I'm not aware how to do that, basically based on if *this is an rvalue reference.

Is such a behaviour possible without resorting to global functions?

CodePudding user response:

If my call was something like sub_structure(f(), ...), I could overload sub_structure by rvalue reference; however, as a class method, I'm not aware how to do that, basically based on if *this is an rvalue reference.

Do you mean overloading on value category? Not sure if this is what you mean, but if get your problem correctly, I'd go this way:

struct S
{
    std::vector<int> data;
    S doStuff() &&
    {
        std::cout << "rvalue\n";
        return {std::move(data)};
    }

    S doStuff() const&
    {
        std::cout << "const lvalue\n";
        return {data};
    } 
};

Demo https://godbolt.org/z/5c89edMKv

This is by no means exhaustive, one can easily return e.g reference to const *this on the const& overload, copy on non-const etc.

  • Related