第42页最下面几行字:

《The C++ Standard Library》第42页 一段很难理解的话

写的莫名其妙。

下面一步一步的分析:

1. The copy constructor指的是:

《The C++ Standard Library》第42页 一段很难理解的话

当执行

《The C++ Standard Library》第42页 一段很难理解的话

的时候,auto_ptr的ownership被从ptr1转移到了ptr2,此时ptr2指向new ClassA所产生的对象,而ptr1就不再指向new ClassA所产生的对象了,而是以空指针作为它的值了,所以说: 《The C++ Standard Library》第42页 一段很难理解的话

其中这里的the object that is used to initialize the new object指的就是ptr1.

2. The assignment operator指的是:

《The C++ Standard Library》第42页 一段很难理解的话

在ptr2=ptr1中,auto_ptr的ownership从 ptr1转移到了ptr2,也就是说,此时ptr2指向new ClassA所产生的对象。

然后,ptr1就不再指向new ClassA所产生的对象了,而是以空指针作为它的值了。所以说:

《The C++ Standard Library》第42页 一段很难理解的话

这里的right-hand side of the assignment 就指的是ptr1.

3. 由于被用来进行copy constructor或者assignment的auto_ptr最后都会指向null,所以最后一句说:

《The C++ Standard Library》第42页 一段很难理解的话

意思就是要这样产生的,指向null的指针不要再被dereference了。

现在另一个问题产生了,怎么样会导致一个变成null的auto_ptr被dereference那?

下面是dereference的定义:

to   get   the   content   which   was   pointed   by   a   pointer   of   a   pointer-like   object   (for   instance   a   iterator)

也就是说,不能再对它进行读取内容之类的操作了。

道理很简单,因为它已经指向null了,这里要提醒我们的是不要忘了这种情况下它已经以空指针作为它的值了,不要再傻乎乎的对它进行操作了,会出大乱子滴

相关文章:

  • 2022-12-23
  • 2021-10-02
  • 2021-10-14
  • 2021-06-18
  • 2021-10-10
  • 2021-06-15
  • 2022-12-23
  • 2022-02-08
猜你喜欢
  • 2021-08-28
  • 2021-05-31
  • 2021-11-26
  • 2021-11-03
  • 2022-01-25
  • 2021-11-20
  • 2021-07-17
相关资源
相似解决方案