Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

13.3 拷贝

再次考虑我们的不完整的vector:

让我们尝试拷贝一个向量:

理想情况下,v2变成v的一个副本(即=意味着拷贝);也就是说,v2.size()==v.size(),且对于所有位于区间[0:v.size())内的整数i有v2[i]==v[i]。并且,对象v2与v所占用的内存将在函数f()结束时被系统回收。这些正是标准库vector所做的(当然是这样),但我们的非常简单的vector还不能实现这些。我们的任务是完善vector使之能够正确处理这个例子,但在此之前,我们首先需要弄清目前的版本都能做什么,准确地说是哪里做错了?如何做错的?为什么?一旦找出了错误所在,我们就很可能解决这些错误。更重要的,当在其他场景中遇到类似问题时,我们就能意识到问题并加以避免。

对一种类型而言,拷贝的默认含义是“拷贝所有的数据成员”。这通常完全讲得通。例如,我们拷贝一个Point对象就是要拷贝其坐标。但对于指针成员而言,仅仅对指针成员进行拷贝会产生问题。特别是,以我们例子中的vector对象为例,这种默认语义意味着拷贝完成后v.sz==v2.sz且v.elem==v2.elem,这样我们的vector对象会像下面这样:

也就是说,v2并未拥有v的元素的副本;它只是共享了v的元素。我们可以写出如下代码: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252