authchir
authchir

Reputation: 1635

Can heap allocated object be move on the stack?

Question

Can we use move semantics to move a heap allocated object on the stack?

Example

#include <boost/asio.hpp>
#include <memory>

class connection
{
public:
    connection(boost::asio::ip::tcp::socket&& socket);

    void start();

private:
    boost::asio::ip::tcp::socket m_socket;
};

class server
{
public:
    // Not relevent here

private:
    void accept();

    boost::asio::io_service        m_io_service;
    boost::asio::ip::tcp::acceptor m_acceptor;
};

void server::accept()
{
    auto socket = new boost::asio::ip::tcp::socket(m_io_service);

    m_acceptor.async_accept(*m_socket,
    [&, socket](const boost::system::error_code& error)
    {
        if (!error)
        {
            auto connection = std::make_shared<connection>(std::move(*socket));
            connection->start();
        }

        accept();
    });
}

Upvotes: 7

Views: 3250

Answers (1)

Kaz
Kaz

Reputation: 58598

std::move does not relocate an object. It moves the value. (Think about a MOV R1, R2 instruction in some machine language: it does not move registers, just the contents! Or the memmove library function. It's that sense of "move", not the kind of move that occurs in copying or compacting garbage collectors, which causes an object to reside at a different address while retaining its exact identity, which involves finding every single reference to the moved object everywhere in the machine and updating it).

move semantics is a new feature in C++ which allows an object to be copied in a way that the old value does not have to be preserved. This is useful in cases when the old object is not going to be needed any more, because it can be faster.

For instance, moving a vector from one std::vector<X> to another can cause the source object to be a zero-length vector, and all the data to move without any memory allocation or copying. Since the idea is that the old vector is not used, it doesn't matter that it has been clobbered to zero length.

There is no reason why this would not work between locations that are in different storage (e.g. free store ("heap") to automatic storage ("stack") given that copy construction between such operands has always worked fine in C++.

[Edit 2020]

However, if we move an object from the heap to somewhere else, we have a problem. The old memory in the heap was just abandoned without any destruction. That memory is no longer an object; to use it again we have to move or construct an object into it. Or else, we have should delete it (in a low-level way, without invoking a destructor).

Upvotes: 9

Related Questions