【cmu15445c++入门】(8)C++ 智能指针unique_ptr

这篇具有很好参考价值的文章主要介绍了【cmu15445c++入门】(8)C++ 智能指针unique_ptr。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

 一、智能指针

智能指针是一种数据结构,用于没有内置内存管理的语言(例如 C++)中的内存管理(有时还有其他功能)。内置内存管理的语言的指的是具有垃圾回收功能的语言,如Java、Python。

现代C++标准库的两个智能指针(以及您将在类中使用的智能指针)是 std::unique_ptr 和 std::shared_ptr。

std::unique_ptr 和 std::shared_ptr 都自动处理内存分配和释放,并在幕后包含原始指针。换句话说,它们是原始指针的包装类。 在这个文件中,我们将讨论 std::unique_ptr。std::unique_ptr 是一种智能指针,保留对象的唯一所有权。

这意味着 std::unique_ptr 的两个实例不能管理同一对象。

 二、代码示例



// A smart pointer is a type of data structure used for memory management (and
// sometimes other features) in languages that don't have memory management
// built in (e.g C++) An example of a language that has memory management built
// in is any language with garbage collection, like Java or Python. Two of the
// modern C++ standard library's smart pointers (and the ones that you will use
// in class) are std::unique_ptr and std::shared_ptr. Both std::unique_ptr and
// std::shared_ptr handle memory allocation and deallocation automatically, and
// contain raw pointers under the hood. In other words, they are wrapper classes
// over raw pointers. In this file, we'll talk about std::unique_ptr.
// std::unique_ptr is a type of smart pointer that retains sole ownership of an
// object This means that no two instances of std::unique_ptr can manage the
// same object.
//智能指针是一种数据结构,用于没有内置内存管理的语言(例如 C++)中的内存管理(有时还有其他功能)。
//内置内存管理的语言的指的是具有垃圾回收功能的语言,如Java、Python。
//现代C++标准库的两个智能指针(以及您将在类中使用的智能指针)是 std::unique_ptr 和 std::shared_ptr。 
//std::unique_ptr 和 std::shared_ptr 都自动处理内存分配和释放,并在幕后包含原始指针。 
//换句话说,它们是原始指针的包装类。 在这个文件中,我们将讨论 std::unique_ptr。 
//std::unique_ptr 是一种智能指针,保留对象的唯一所有权。
//这意味着 std::unique_ptr 的两个实例不能管理同一对象。

// Includes std::cout (printing) for demo purposes.
#include <iostream>
// Includes std::unique_ptr functionality.
#include <memory>
// String library for printing help for demo purposes.
#include <string>
// Including the utility header for std::move.
#include <utility>

// Basic point class. (Will use later)
class Point {
public:
  Point() : x_(0), y_(0) {}
  Point(int x, int y) : x_(x), y_(y) {}
  inline int GetX() { return x_; }
  inline int GetY() { return y_; }
  inline void SetX(int x) { x_ = x; }
  inline void SetY(int y) { y_ = y; }

private:
  int x_;
  int y_;
};

// Function that takes in a unique pointer reference and changes its x value to
// 445.
void SetXTo445(std::unique_ptr<Point> &ptr) { ptr->SetX(445); }

int main() {
  // This is how to initialize an empty unique pointer of type
  // std::unique_ptr<Point>.
  std::unique_ptr<Point> u1;
  // This is how to initialize a unique pointer with the default constructor.
  std::unique_ptr<Point> u2 = std::make_unique<Point>();
  // This is how to initialize a unique pointer with a custom constructor.
  std::unique_ptr<Point> u3 = std::make_unique<Point>(2, 3);

  // Here, for std::unique_ptr instance u, we use the statement (u ? "not empty"
  // : "empty") to determine if the pointer u contains managed data. The main
  // gist of this is that the std::unique_ptr class has a conversion function on
  // its objects to a boolean type, and so this function is called whenever we
  // treat the std::unique_ptr as a boolean. For instance, this can be used in
  // the following example.

  // 通过判断u是否为空,决定u是否包含包含托管数据。 
  // 此处的要领是,unique_ptr具有转换函数,能够把对象转为bool型
  // 所以,每当我们将 std::unique_ptr 视为布尔值时,就会调用此函数。
  if (u1) {
    // This won't print because u1 is empty.
    std::cout << "u1's value of x is " << u1->GetX() << std::endl;
  }

  if (u2) {
    // This will print because u2 is not empty, and contains a managed Point
    // instance.
    std::cout << "u2's value of x is " << u2->GetX() << std::endl;
  }

  // Note that u1 is empty and u2 and u3 are not empty, since they were
  // initialized with a Point instance.
  std::cout << "Pointer u1 is " << (u1 ? "not empty" : "empty") << std::endl;
  std::cout << "Pointer u2 is " << (u2 ? "not empty" : "empty") << std::endl;
  std::cout << "Pointer u3 is " << (u3 ? "not empty" : "empty") << std::endl;

  // Since instances of std::unique_ptr can have only one owner, it has no copy
  // constructor. Therefore, this code won't compile. Uncomment it to try!
  // 因为unique_ptr只能有一个owener,没有copy类型的构造方法。所以,下面的代码编译不通过
  // std::unique_ptr<Point> u4 = u3;


  // However, it's possible to transfer ownership of unique pointers via——通过move函数可以
  // std::move.
  std::unique_ptr<Point> u4 = std::move(u3);

  // Note that because u3 is an lvalue, it no longer contains any managed
  // object. It is an empty unique pointer. Let's retest for emptyness.
  // move之后,u3已经不包含任何对象。
  std::cout << "Pointer u3 is " << (u3 ? "not empty" : "empty") << std::endl;
  std::cout << "Pointer u4 is " << (u4 ? "not empty" : "empty") << std::endl;

  // Lastly, let's talk about how to pass std::unique_ptr instances as arguments
  // to functions. Mainly, you should pass it as a reference so that the
  // ownership doesn't change. You can see this as an example in the function
  // SetXTo445 (line 44 in this file).
  SetXTo445(u4);

  // Now, let's print the x value of u4 to confirm that the change occured, but
  // the ownership of the Point instance has been retained to u4.
  std::cout << "Pointer u4's x value is " << u4->GetX() << std::endl;

  return 0;
}

三、运行结果

【cmu15445c++入门】(8)C++ 智能指针unique_ptr,C/C++,c++文章来源地址https://www.toymoban.com/news/detail-831150.html

到了这里,关于【cmu15445c++入门】(8)C++ 智能指针unique_ptr的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C++11补充:智能指针如std::unique_ptr如何添加自定义的deleter

    关于智能指针的问题,有时候为了方便,需要在析构时附加一些清理操作,或者,有的指针本身来自C的库文件中,这时候,就非常期望能够使用自定义的deleter, 但是标准C++创建函数如std::make_unique / std::make_shared 等不支持创建带有自定义deleter的智能指针,这时,我们只能使用

    2024年02月07日
    浏览(32)
  • shared_ptr和unique_ptr主动释放

    shared_ptr和unique_ptr均可以采用reset()来进行释放,unique_ptr调用了reset之后就会直接释放掉,shared_ptr则会在所有引用计数变为0的时候才会释放申请的内存。 注意unique_ptr的release()方法,并不会释放资源,只会把unique_ptr置为空指针,原来那个资源可以继续调用 reset 结果: 在reset之

    2024年02月14日
    浏览(28)
  • 面试之快速学习C++11-完美转发,nullptr, shared_ptr,unique_ptr,weak_ptr,shared_from_this

    函数模版可以将自己的参数完美地转发给内部调用的其他函数。所谓完美,即不仅能准确地转发参数的值,还能保证被转发参数的左右值属性不变 引用折叠:如果任一引用为左值引用,则结果为左值引用,否则为右值引用。 上述 T 为int 。 那么整个为 int - int 回到完美转发,

    2024年02月12日
    浏览(24)
  • 【cmu15445c++入门】(4)c++中的模板方法

    模板方法是c++的一个特性,可以让你的代码在不指定数据类型的情况下,运行不同的数据类型。 你可以创建模板方法和模板类,本文讨论模板方法。

    2024年02月02日
    浏览(20)
  • 【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]

    在 C++ 动态内存管理中,除了 auto_ptr 和 unique_ptr 之外,还有一种 智能指针 shared_ptr ,它可以让多个指针共享同一个动态资源,并且能够自动释放资源。 shared_ptr 通过引用计数的方式来管理内存,能够避免程序中出现悬空指针和内存泄漏等问题 。本文将介绍 shared_ptr 的简介和

    2024年01月22日
    浏览(38)
  • CMU15445(2023 spring) lab - 环境配置

    环境配置 Project 0. C++ Primer Project 1. Buffer Pool Project 2. B+Tree 早就想做15445(fall 2020)的lab了,鸽到了现在,赶紧做一下,写一点自己做的时候遇到的坑什么的,记录一下。因为教授禁止上传自己的代码到public,所以本文基本不会出现作业代码内容,只是写一些做的时候遇到的事

    2024年02月05日
    浏览(24)
  • CMU15445 (Spring 2023) #Project0

    写这篇文章,初衷是因为网上很少有关于CMU15445-2023的博客文章。记录下我在做的过程中走过的弯路,一方面是对自己工作的一个总结,另一方面也能帮助到在做这门课的 #project 时踩坑而无从下手的同学,何乐而不为? 我使用的编译环境: 系统:Ubuntu 20.04.1 IDE:Clion 语法要求

    2024年02月09日
    浏览(26)
  • 智能指针shared_ptr

    shared_ptr共享它指向的对象,内部采用计数机制来实现。当新的shared_ptr与对象关联时,引用计数加1;当shared_ptr超出作用域时,引用计数减1;当引用计数为0时,释放该对象; shared_ptrA p0 = std::make_sharedA(\\\"西红柿\\\");//C++11提供 重载了*和-操作符,可以像使用指针一样使用shared_ptr

    2023年04月23日
    浏览(31)
  • CMU15445 (Fall 2020) 之 Project#1 - Buffer Pool 详解

    去年暑假完成了 CMU15-445 Fall 2019 的四个实验,分别对应下述博客: CMU15445 (Fall 2019) 之 Project#1 - Buffer Pool 详解 CMU15445 (Fall 2019) 之 Project#2 - Hash Table 详解 CMU15445 (Fall 2019) 之 Project#3 - Query Execution 详解 CMU15445 (Fall 2019) 之 Project#4 - Logging Recovery 详解 今年打算接着完成 Fall 2020 的四个

    2024年02月08日
    浏览(27)
  • C++智能指针shared_ptr详解

    C++智能指针shared_ptr是一种可以自动管理内存的智能指针,它是C++11新增的特性之一。与传统指针不同,shared_ptr可以自动释放所管理的动态分配对象的内存,并避免了手动释放内存的繁琐操作,从而减少了内存泄漏和野指针的出现。 shared_ptr是一个模板类,通过引用计数器实现

    2023年04月22日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包