Class 对象 unique_ptr 重置,销毁/构造顺序

Class object unique_ptr reset, order of destruction / construction

我有一个 unique_ptr 的矢量用于 ethernet_socket class。如果我重置指针,我会在析构函数之前看到我的日志中首先调用的构造函数。这是正确的,还是我的提升日志记录滞后?

伪代码

std::vector <boost::movelib::unique_ptr<eth_socket> > _eth_socket_vect;
_eth_socket_vect.resize(1);
_eth_socket_vect.at(0).reset(new eth_socket(host, port, delimiter, timeout, 1));     
// destructor is not called on first reset

// do some operations, then reset

_eth_socket_vect.at(0).reset(new eth_socket(host, port, delimiter, timeout, 1));

// do some more operations on new object

调用第二次重置的日志

20-02-28 08:44:14.312702 [info] src/eth_socket.cpp(eth_socket:10) >> started; host_num = 1  <---CONSTRUCTOR
20-02-28 08:44:14.312825 [info] src/eth_socket.cpp(open_eth_socket:67) >> started; host_num = 0
20-02-28 08:44:14.312869 [info] src/eth_socket.cpp(open_eth_socket:71) >> socket_host = 10.0.0.4; socket_port = 1337; host_num = 0
20-02-28 08:44:14.313016 [info] src/eth_socket.cpp(open_eth_socket:104) >> ended; host_num = 0
20-02-28 08:44:14.313054 [info] src/eth_socket.cpp(read_data:247) >> started; host_num = 0
20-02-28 08:44:14.313089 [info] src/eth_socket.cpp(read_data:275) >> ended; host_num = 0
20-02-28 08:44:14.313109 [info] src/eth_socket.cpp(eth_socket:38) >> ended; host_num = 1
20-02-28 08:44:14.313132 [info] src/eth_socket.cpp(~eth_socket:43) >> started; host_num = 0  <-- DESTRUCTOR
20-02-28 08:44:14.313225 [info] src/eth_socket.cpp(close_eth_socket:113) >> started; host_num = 0
20-02-28 08:44:14.313287 [info] src/eth_socket.cpp(socket_read_data_callback:368) >> started; host_num = 0
20-02-28 08:44:14.313299 [info] src/eth_socket.cpp(close_eth_socket:144) >> ended; host_num = 0
20-02-28 08:44:14.313327 [info] src/eth_socket.cpp(~eth_socket:58) >> ended; host_num = 0

当您调整 vector 的大小时,其元素包含空 unique_ptr(相当于 nullptr):

std::vector <boost::movelib::unique_ptr<eth_socket> > _eth_socket_vect;
_eth_socket_vect.resize(1);

现在您创建了一个 eth_socket 的实例,因此调用了它的构造函数:

_eth_socket_vect.at(0).reset(new eth_socket(host, port, delimiter, timeout, 1));     

然后您创建另一个实例并替换之前的实例。所以,首先调用 eth_socket 构造函数,然后调用前一个实例的析构函数:

_eth_socket_vect.at(0).reset(new eth_socket(host, port, delimiter, timeout, 1));