unique_ptr通过禁止拷贝和允许移动来保证资源独占所有权,其核心机制包括:1. 显式删除拷贝构造函数和赋值运算符,防止多个unique_ptr指向同一资源;2. 提供移动构造函数和移动赋值运算符,允许资源所有权转移,原指针变为nullptr;3. 析构函数自动释放资源,确保资源只被释放一次。移动语义使资源可在不同unique_ptr间高效转移,而无需拷贝,是其实现独占语义的关键支撑。

unique_ptr
unique_ptr

unique_ptr

unique_ptr
unique_ptr
立即学习“C++免费学习笔记(深入)”;
禁止拷贝构造和拷贝赋值:
unique_ptr
= delete
unique_ptr
unique_ptr
unique_ptr

#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr1(new int(10));
// std::unique_ptr<int> ptr2 = ptr1; // 错误:拷贝构造函数被删除
return 0;
}允许移动构造和移动赋值:虽然不能拷贝,但
unique_ptr
unique_ptr
unique_ptr
unique_ptr
nullptr
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr1(new int(10));
std::unique_ptr<int> ptr2 = std::move(ptr1); // OK:移动构造
if (ptr1 == nullptr) {
std::cout << "ptr1 is now null" << std::endl; // 输出:ptr1 is now null
}
std::cout << *ptr2 << std::endl; // 输出:10
return 0;
}析构函数释放资源:当
unique_ptr
unique_ptr
unique_ptr
C++11引入的移动语义是
unique_ptr
unique_ptr
unique_ptr
unique_ptr
如果没有移动语义,
unique_ptr
具体来说,移动语义通过以下方式在
unique_ptr
移动构造函数:移动构造函数接受一个右值引用作为参数,它会将右值引用的资源的所有权转移到新创建的对象。在
unique_ptr
unique_ptr
nullptr
unique_ptr
移动赋值运算符:移动赋值运算符也接受一个右值引用作为参数,它会将右值引用的资源的所有权转移到当前对象。在
unique_ptr
unique_ptr
unique_ptr
nullptr
unique_ptr
下面是一个更详细的例子,展示了移动语义在
unique_ptr
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called" << std::endl;
}
};
int main() {
std::unique_ptr<MyClass> ptr1(new MyClass()); // 构造MyClass对象
std::unique_ptr<MyClass> ptr2 = std::move(ptr1); // 移动所有权
if (ptr1 == nullptr) {
std::cout << "ptr1 is now null" << std::endl; // 输出:ptr1 is now null
}
// ptr2拥有资源,当ptr2销毁时,MyClass的析构函数会被调用
return 0; // 程序结束时,ptr2被销毁,MyClass析构函数被调用
}unique_ptr
unique_ptr
unique_ptr
另外,
unique_ptr
unique_ptr
unique_ptr
默认情况下,
unique_ptr
delete
你可以通过在
unique_ptr
#include <iostream>
#include <memory>
// 使用函数指针作为删除器
void myDeleter(int* ptr) {
std::cout << "Custom deleter called" << std::endl;
delete ptr;
}
// 使用函数对象作为删除器
struct MyDeleter {
void operator()(int* ptr) {
std::cout << "Custom deleter functor called" << std::endl;
delete ptr;
}
};
int main() {
std::unique_ptr<int, void(*)(int*)> ptr1(new int(10), myDeleter); // 使用函数指针
std::unique_ptr<int, MyDeleter> ptr2(new int(20), MyDeleter()); // 使用函数对象
// 使用lambda表达式作为删除器
std::unique_ptr<int, std::function<void(int*)>> ptr3(new int(30), [](int* ptr) {
std::cout << "Custom deleter lambda called" << std::endl;
delete ptr;
});
return 0; // 程序结束时,会调用自定义的删除器
}unique_ptr
unique_ptr
管理动态分配的内存:这是
unique_ptr
实现RAII原则:
unique_ptr
unique_ptr
作为工厂函数的返回值:工厂函数通常用于创建对象。使用
unique_ptr
在容器中存储对象:
unique_ptr
vector
list
总之,
unique_ptr
以上就是unique_ptr怎样实现独占所有权 详解C++移动语义在智能指针中的应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号