LoopPerfect / neither

Either and Maybe monads for better error-handling in C++ ↔️
MIT License
249 stars 18 forks source link

Move Semantics for Either #11

Closed nikhedonia closed 7 years ago

nikhedonia commented 7 years ago

We should have an overload for move semantics for either. However we need to be careful here. Move mutates the state of the referenced object by making it potentially invalid. In case of an Either this should be only allowed if Either itself is movable to make Either behave like an valuetype.

In c++ this semantics can be expressed via:

#include <iostream>
#include <string>

struct Test {
    constexpr int get() const& { return 1; }   
    constexpr int get()&& { return 0; }    // if object is a temporary
};

int main()
{
    Test x;
    std::cout << "const&, " << x.get() << "!\n";
    std::cout << "&& " << Test{}.get() << "!\n";
}

// http://cpp.sh/6tnb6

Why is this Important? - consider the following example:

Eiher<int, unique_ptr<int>> e = right(make_unique(5));

auto e2 = e.rightMap([](auto&& ptr) { return ptr; });
auto e3 = e.rightMap([](auto&& ptr) { return ptr; });

e2.rightMap([](auto&& ptr) { return ptr.get() == 5; }); // right(true);
e2.rightMap([](auto&& ptr) { return ptr.get() == 5; }); // segfault: ptr is not valid anymore