Releasing memory with std::move()?

563 views Asked by At

Says I have a class with a standard container:

class Library{
    std::vector<Book> books;
public:
    void putOnFire(){
        books.clear();
    }
};

The usual way to clear a container is "clear", however most code is not "STL compliant" so many containers (by third parties) may not have a "clear" method. however, If they have move semantics I could just use std::move right?

void putOnFire(){
    auto p = std::move(books); //books cleared when p out of scope
}

this is to write most generic possible code that works also with something that is not a STL container with a "clear" method.

3

There are 3 answers

0
example On BEST ANSWER

std::move leaves the moved-from object in a valid but unspecified state. In particular it might stay exactly the way it was before, so while this might actually work with your implementation of the stl, it will certainly not work for all third-party containers. (And might break at any point in the future when your implementation of the stl changes due to an update)

0
M.M On

The vector can have its memory released:

void putOnFire()
{
    books.clear();
    books.shrink_to_fit();
}

If you are working with some container that is not a standard container then you'll have to consult its documentation to see what operations it supports.

Writing code that anticipates a container with an unknown interface is just not possible.

2
erenon On

I wouldn't recommend this. First, it obscures the intention. Either use c.clear or c.erase(c.begin(), c.end()). A container without a way to erase/remove elements is not a proper dynamically sized container. Also your proposed solution depends on the move constructor of the specific container type, which is implementation defined, no memory must be freed.

As a last resort, I'd recommend using swap instead of the suggested move.