C++ 的 unique_ptr 智能指针

等级 4205 次按键

unique_ptr 拥有一个 Resource,并在离开作用域时自动删除它,因此依次输出 Created、Using resource、Destroyed。

C++ 代码

1class Resource {
2public:
// 构造函数输出 Created
3 Resource() { cout << "Created" << endl; }
// 析构函数输出 Destroyed
4 ~Resource() { cout << "Destroyed" << endl; }
5};
6
// 开始一个限定指针生命周期的块
7{
// make_unique 创建 Resource(输出 Created),ptr 成为它唯一的所有者
8 unique_ptr<Resource> ptr = make_unique<Resource>();
// 在对象仍然存在时输出 Using resource
9 cout << "Using resource" << endl;
// ptr 在此离开作用域并删除 Resource:输出 Destroyed
10}

运行结果

Created
Using resource
Destroyed
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 14
  • "× 6
  • ;× 5
  • {× 4
  • }× 4
  • (× 3
  • )× 3
  • _× 2
  • >× 2
  • :× 1

C++ 等级 4 的更多代码示例

← 返回 C++ 打字练习