std::unique_ptr通过移动语义实现资源唯一所有权的转移,支持使用std::move进行移动赋值,函数返回时自动应用移动语义,类成员间也可通过移动传递资源,原指针移动后变为nullptr。

在C++中,std::unique_ptr 是一种独占式智能指针,不支持拷贝构造和赋值,但支持移动语义。通过移动赋值操作,可以将一个 unique_ptr 管理的资源“转移”给另一个 unique_ptr,原指针变为 nullptr。
使用 std::move() 可以触发移动赋值操作:
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);
std::unique_ptr<int> ptr2;
std::cout << "ptr1 value: " << *ptr1 << "\n"; // 输出 42
ptr2 = std::move(ptr1); // 移动赋值
if (ptr1 == nullptr) {
std::cout << "ptr1 is now null\n";
}
std::cout << "ptr2 value: " << *ptr2 << "\n"; // 输出 42
}
函数返回 unique_ptr 时,编译器通常会自动应用移动语义:
std::unique_ptr<int> createValue() {
return std::make_unique<int>(100);
}
int main() {
std::unique_ptr<int> ptr = createValue(); // 自动移动,无需 std::move
std::cout << "Value: " << *ptr << "\n"; // 输出 100
}
在类之间传递 unique_ptr 资源时,常使用移动赋值:
立即学习“C++免费学习笔记(深入)”;
class Container {
public:
std::unique_ptr<int> data;
void setData(std::unique_ptr<int> new_data) {
data = std::move(new_data); // 接收所有权
}
};
int main() {
Container c;
auto temp_ptr = std::make_unique<int>(50);
c.setData(std::move(temp_ptr)); // 转移所有权
// temp_ptr 已为空
if (!temp_ptr) {
std::cout << "temp_ptr is null after move\n";
}
std::cout << "Container's data: " << *c.data << "\n"; // 输出 50
}
基本上就这些。移动赋值让 unique_ptr 在保持唯一所有权的同时,具备灵活的资源传递能力。记住:一旦发生移动,原指针变空,不能再解引用。
以上就是C++unique_ptr移动赋值操作示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号