std::unique_ptr 是C++11 引入的智能指针,用于管理动态分配的对象(包含数组对象),确保对象在超出作用域时被自动释放。 以下是 std::unique_ptr 的一些基本用法示例: 1. 基本用法 #include <memory> #include <iostream> void example() { // 创建一个 unique_ptr 管理动态分配的
与std::unique_ptr不同,std::shared_ptr允许多个智能指针共享同一个对象。它通过引用计数来实现这一点,即当一个新的std::shared_ptr指向一个对象时,该对象的引用计数加一,当一个std::shared_ptr被销毁时,该对象的引用计数减一,当引用计数达到0时,对象会被自动销毁。 std::shared_ptr<int> ptr1(new int(5...
std::unique_ptr是一种独占的语义,即只允许一个智能指针引用裸指针,这区别于std::shared_ptr允许多个shared_ptr引用同一个裸指针,它没有引用计数,它的性能比shared_ptr会高一点。 在用法上std::unique_ptr和std::shared_ptr是类似的,主要的不同是std::unique_ptr之间的赋值需要通过std::move实现。 在code2 ...
if (!ptr1) { std::cout << "ptr1 is empty" << std::endl; } //检查unique_ptr对象是否为空 if (ptr1 == nullptr) { std::cout << "ptr1 is empty" << std::endl; } //不能通过赋值初始化创建unique_ptr对象 //std::unique_ptr<Task> taskPtr2 = new Task(); //编译错误 ...
可能你还是很疑惑std::weak_ptr怎样使用呢。设想一个工厂函数,基于唯一ID来创建一些指向只读对象的灵巧指针。根据条款18对工厂函数返回类型的建议,应该返回一个 std::unique_ptr: std::unique_ptr<const Widget> loadWidget(WidgetID id); 假如loadWidget是一个昂贵的调用(比如因为涉及到文件而且。然而保持每一个...
std::unique_ptr的一个常见用法是在对象继承谱系中作为工厂函数的返回型别。这种继承谱系的工厂函数通常会在堆上分配一个对象并且返回一个指涉到它的指针,并当不在需要该对象时,由调用者负责删除之。 三、示例(以下代码需要c++14支持) #ifndefUNIQUEPTRDEMO_H#defineUNIQUEPTRDEMO_H#include<iostream>#include<memo...
std::unique_ptr 是一种独占的语义,即只允许一个智能指针引用裸指针,这区别于 std::shared_ptr 允许多个 shared_ptr 引用同一个裸指针,它没有引用计数,它的性能比 shared_ptr 会高一点。
std::unique_ptr的用法 std::ofstream("demo.txt") <<'x';//准备要读的文件{ std::unique_ptr<std::FILE, decltype(&std::fclose)> fp(std::fopen("demo.txt","r"),&std::fclose);if(fp)//fopen 可以打开失败;该情况下 fp 保有空指针std::cout << (char)std::fgetc(fp.get()) <<'\n...