我正在尝试为具有两个仅 move 成员的类编写 move 构造函数。困难在于其中一个成员持有对另一个成员的引用,因此一旦它们都被 move ,其中一个成员就会引用一个不再存在的对象:
class Server : noncopyable
{
};
class Client : noncopyable
{
public:
Client(Server& server) : server_(server) {}
Client(Client&& other) : server_(std::move(other.server_)) {}
std::reference_wraper<Server> server_;
};
class MyClass : noncopyable
{
public:
MyClass()
: server_(),
client_(server_) {}
// destroys other.server_ which client uses before and after move
MyClass(MyClass&& other)
: server_(std::move(other.server_)),
client_(std::move(other.client_))
private:
Server server_;
Client client_;
};
遇到这种情况有什么好的办法吗?基本上,引用对象在 move 时需要将其引用更新为 move 到的版本。
最佳答案
解决这个问题最简单的方法是 Kiss MyClass
的值成员再见。
如果您只是使用std::unique_ptr<Server>
和std::unique_ptr<Client>
相反,剩下的就很自然了 - 正如 Server
对象本身永远不会 move ,只是 MyClass
所持有的指向它的指针被 move 。 ,您不需要更新 Client
中的任何内容.
关于c++ - 如何将相互依赖的对象 move 在一起并维护内部引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20492629/