在 C++ 中使用智能指针
本文将演示如何在 C++ 中使用智能指针的多种方法。
对多个指针使用 std::shared_ptr
可以引用 C++ 中的同一对象
由于动态内存的手动管理在现实世界的项目中非常困难,并且通常是导致错误的主要原因,因此 C++ 提供了智能指针的概念作为单独的库。智能指针通常充当常规指针,并提供额外的功能,其中最突出的功能是自动释放指向的对象。智能指针有两种核心类型:shared_ptr
和 unique_ptr
。
以下示例代码演示了 shared_ptr
类型的用法。请注意,当指向的对象应由其他共享指针引用时,通常会使用 shared_ptr
。因此,shared_ptr
在内部具有关联的计数器,该计数器表示指向同一对象的指针的数量。shared_ptr::unique
成员函数可用于确定指针是否仅是引用当前对象的一个。函数返回类型为布尔值,而 true
值确认对象的专有所有权。内置的 reset
函数将当前对象替换为作为第一个参数传递的对象。当最后一个指向该对象的 shared_ptr
超出范围时,该共享对象将被删除。
#include <iostream>
#include <vector>
#include <memory>
using std::cout; using std::vector;
using std::endl; using std::string;
int main() {
std::shared_ptr<string> p(new string("Arbitrary string"));
std::shared_ptr<string> p2(p);
cout << "p : " << p << endl;
cout << "p2: " << p2 << endl;
if (!p.unique()) {
p.reset(new string(*p));
}
cout << "p : " << p << endl;
*p += " modified";
cout << "*p : " << *p << endl;
cout << "*p2 : " << *p2 << endl;
return EXIT_SUCCESS;
}
输出:
p : 0x2272c20
p2: 0x2272c20
p : 0x2273ca0
*p : Arbitrary string modified
*p2 : Arbitrary string
在 C++ 中使用 std::unique_ptr
来获得一个拥有给定对象的指针
另外,C++ 提供了 unique_ptr
类型,它是对象的唯一所有者。没有其他 unique_ptr
指针可以引用它。unique_ptr
不支持普通的复制和赋值操作。仍然可以使用内置函数 release
和 reset
在两个 unique_ptr
指针之间转移对象所有权。release
函数调用使 unique_ptr
指针为空。一旦释放了 unique_ptr
,便可以调用 reset
函数来为其分配新的对象所有权。
#include <iostream>
#include <vector>
#include <memory>
using std::cout; using std::vector;
using std::endl; using std::string;
int main() {
std::unique_ptr<string> p1(new string("Arbitrary string 2"));
std::unique_ptr<string> p3(p1.release());
cout << "*p3 : " << *p3 << endl;
cout << "p3 : " << p3 << endl;
cout << "p1 : " << p1 << endl;
std::unique_ptr<string> p4(new string("Arbitrary string 3"));
p3.reset(p4.release());
cout << "*p3 : " << *p3 << endl;
cout << "p3 : " << p3 << endl;
cout << "p4 : " << p4 << endl;
return EXIT_SUCCESS;
}
输出:
*p3 : Arbitrary string 2
p3 : 0x7d4c20
p1 : 0
*p3 : Arbitrary string 3
p3 : 0x7d5c80
p4 : 0
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。