首页 > 解决方案 > 包含唯一指针成员变量的类的 C++ 赋值运算符

问题描述

我知道,如果我有一个带有智能唯一指针的类,则无法将该类分配给另一个实例,因为无法复制唯一指针。我知道我可以使唯一指针成为共享指针,这将解决问题。但是,如果我不想共享指针的所有权怎么办?是否可以创建一个赋值运算符来移动唯一指针并复制其他变量?

我读过你可以std::move用来传递所有权。

#include <iostream>
#include <memory> 

struct GraphStructure { };

class test {

        int a;
        std::vector<int> vector;
        std::unique_ptr<GraphStructure> Graph_; 
 };

 int main () {

     test t1;
     auto t2 = t1;
 }

标签: c++unique-ptrassignment-operator

解决方案


The default copy constructor of class test is deleted because of a member (graph_) not being copiable (if you still could copy in any meaningful way, e. g. by creating a deep copy of the graph member, you'd have to implement on your own copy constructor). In contrast, the default move constructor still exists (std::unique_ptr is movable). So what you can do is the following:

test t1;
auto t2 = std::move(t1);

Be aware, though, that t1 then won't hold any object any more (you moved the object, so you moved its contents to another one) and the object previously held by t2 is destroyed. If this is a meaningful state is up to you to decide...

Side note: What I wrote about copy and move constructors applies for copy and move assignment as well...


推荐阅读