c++ - 包含唯一指针成员变量的类的 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;
}
解决方案
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...
推荐阅读
- perl - 仅打印最近的文件
- python - 将值更改为数组会导致 NAN
- c# - 在非无头模式下执行 Selenium Grid
- android - 如何使用 Scrollview 和 LinearLayout 设计 BottomNavigationView
- batch-file - 时间环境变量未按预期工作
- javascript - Firebase Auth(javascript):链接帐户时出现“TypeError:user.delete 不是函数”
- python - 通过 Ansible 替换 YAML 文件中的 SSH 密钥
- c# - AspNet 核心集成测试 - MethodNotAllowed 响应
- java - 在服务器上部署 Web 应用程序后,我收到网页未找到错误
- python - Django 高效的一对多链查找