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.2 拷贝赋值

我们可以通过构造函数拷贝(初始化)对象,但我们也可以通过赋值的方式拷贝vector。与拷贝初始化类似,默认的拷贝赋值是逐成员的拷贝。因此,对于我们目前定义的vector,拷贝赋值会造成双重释放(如13.2.1节中的拷贝构造函数所示)以及内存泄漏问题。例如:

我们希望v2成为v的副本(标准库vector就是这样做的),但由于我们并未给vector定义拷贝赋值操作,因此将执行默认的拷贝赋值操作;即赋值操作将进行逐成员拷贝,因此,v2的sz、elem将会与v的sz、elem完全相同,如下所示:

当我们离开f2()时,将会发生灾难性错误,与13.2节中我们添加拷贝构造函数之前离开f()时一样:被v与v2共同指向的元素将被释放两次(使用delete[])。另外,还会发生内存泄漏:我们“忘记了”释放最初为v2的四个元素所分配的内存。对拷贝赋值操作的改进本质上与对拷贝初始化的改进(见13.2.1节)完全相同。我们应像下面代码这样恰当定义拷贝赋值操作:

赋值比构造稍微复杂一些,因为我们必须处理旧有元素。我们的基本策略是创建源vector元素的一份拷贝: ...

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