Correct idiom for allocating and deallocating resources via C interface
<p>Often C++ programs have to deal with C libraries providing free functions for allocating and freeing a resource. To simplify this example, think about two C functions like <code>get_resource()</code> and <code>free_resource()</code>.</p>

<p>Consider an object getting any resource at some point of its life and automatically freeing it once the object is destroyed or not fully constructed because of an error during the construction.</p>

<p>What is an ideal/short/simple idiom for obtaining that automatism? An idea is the following, but it makes the object not properly default-moveable. Is there anything better which does not imply freeing memory from within the destructor or checking errors in the constructor to do rollbacks?</p>

<pre><code>struct Object {
    void* my_get_resource() { // might be called from the constructor or any other point
        return get_resource();
    }

    Object() : up(&amp;resource, &amp;del) { 
        resource = my_get_resource();
        /* init all the stuff, but this init might fail at _many_ points */ 
    }
    //~Object() { if (resource) free_resource(resource); } // I don't like: collides with del and is not called if my_get_resource() is called from the constructor and the init process fails for some reasons

private:
    void *resource = nullptr;
    static void del(void ** ) noexcept {
        if (*resource) { free_resource(resource); }
    }
    unique_ptr &lt; void*, decltype(&amp;del) &gt; up; // RAII: almost good, sadly that makes Object not moveable properly without redefining the move constructor properly


};
</code></pre>
