0

I am playing around with immutable objects after reading the excellent Functional Programming in C++ book. Assume I have a class for an immutable vector like this:

template<typename T>
class immutable_vector
{
public:
   immutable_vector() {}

immutable_vector<T> push_back(const T& t) const &
{
    immutable_vector result(*this);
    result.data.push_back(t);
    return result;
}

//What is the best way to implement this? (see below)
immutable_vector<T> push_back(const T& t) &&;

private:
   std::vector<T> data;

};

I know that this is a dumb way of implementing the immutable vector, but this is not the point of the question. My question is on how to implement the rvalue qualified member function push_back.

Variant 1

immutable_vector<T> push_back(const T & t) &&
{
    data.push_back(t);
    return std::move(*this);
}

Variant 2

immutable_vector<T> push_back(const T & t) &&
{
    immutable_vector<T> result(std::move(*this));
    result.data.push_back(t);
    return result;
}

This is the way the author of the book does it.

My Question

Is one way better than the other or are they completely equivalent?

My guess was that they would be equivalent, because in both cases the move constructor is called once. I would also assume that in Variant 2 copy elision would take place so that no additional constructors would be called. Am I missing something?

geo
  • 361
  • 1
  • 9
  • Perhaps irrelevant, but aren't both variants missing `const`? Shouldn't the signature be `immutable_vector push_back(const T & t) const &&`? – Ted Lyngmo Mar 01 '20 at 12:21
  • I thought that using const here would prevent me from mutating the contained vector. Which is what I want to do. – geo Mar 01 '20 at 12:25
  • I see, and why then return a new instance of `immutable_vector`? It mutates, but returns a copy of the mutation. It feels like an utterly confusing interface. The name `immutable` on something that mutates doesn't help. – Ted Lyngmo Mar 01 '20 at 12:29
  • I agree that this is not a good immutable vector implementation. But the point of my question was the difference between the variants. I am interested in taking advantage of move semantics for immutable data structures. – geo Mar 01 '20 at 12:55

0 Answers0