Skip to content

Instantly share code, notes, and snippets.

@kaeluka
Created February 27, 2016 13:00

Revisions

  1. Stephan Brandauer created this gist Feb 27, 2016.
    30 changes: 30 additions & 0 deletions moving_unique_ptr.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    class A {};

    // Proof of concept.
    //
    // A class that wraps a unique_ptr and creates a copy constructor that
    // allows you to copy it without the explicit move constructor.
    // The move constructor will be implied. This violates the expectation
    // that copying a value is free of side effects and you should therefore
    // probably not use this class.
    template <class T> struct moving_unique_ptr {
    moving_unique_ptr(std::unique_ptr<T> _p) : p(move(_p)) { }

    moving_unique_ptr(const moving_unique_ptr &other) {
    this->p = std::move(const_cast<moving_unique_ptr &>(other).p);
    }
    private:
    std::unique_ptr<T> p;
    };

    moving_unique_ptr<A> f() { return moving_unique_ptr<A>(std::make_unique<A>()); }

    void g(moving_unique_ptr<A> a) {}

    int main() {
    // this works automatically
    g(f());
    moving_unique_ptr<A> a = f();
    // this needs a move
    g(a);
    }