Is it possible to move the selected object onto the stack?

Question

Is it possible to use move semantics to move the selected heap of an object onto 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(); }); } 
+6
source share
1 answer

std::move does not move the object. It moves the meaning. (Think of the MOV R1, R2 instruction in some machine language: it does not move the registers, just the contents! Or the memmove library function. This is a feeling of "moving", and not what happens when copying or compressing garbage collectors that force an object be at a different address, while maintaining its accurate identification, which includes searching for every link to a moved object everywhere on the machine and updating it).

move semantics is a new function in C ++ that allows you to copy an object in such a way that the old value does not need to be saved. This is useful in cases where the old object is no longer needed, because it can be faster.

For example, moving a vector from one std::vector<X> to another can cause the original object to be a zero-length vector, and all data will be moved without any memory allocation or copying. Since the idea is that the old vector is not used, it does not matter that it has been flattened to zero length.

There is no reason why this will not work between locations located in different repositories (for example, free storage ("heap") for automatic storage ("stack"), given that building a copy between such operands always worked fine in C ++ .

+8
source

Source: https://habr.com/ru/post/913680/


All Articles