Skip to Content
Effective Modern C++(中文版)
book

Effective Modern C++(中文版)

by Scott Meyers
April 2018
Intermediate to advanced
303 pages
4h 54m
Chinese
China Electric Power Press Ltd.
Content preview from Effective Modern C++(中文版)
智能指针
115
条款
18
:使用
std::unique_ptr
管理具备专属所
有权的资源
每当你需要使用智能指针时,
std::unique_ptr
基本上应是手头首选。可以认为在默
认情况下
std::unique_ptr
和裸指针有着相同的尺寸,并且对于大多数的操作(包
括提领),它们都是精确地执行了相同的指令。这就意味着你甚至在内存和时钟周期
紧张的场合下使用
std::unique_ptr
。如果裸指针对你来说足够小并且足够快,那么
std::unique_ptr
几乎可以肯定也能满足你的要求。
std::unique_ptr
实现的是专属所有权语义。一个非空的
std::unique_ptr
总是拥有
其所指涉到的资源。移动一个
std::unique_ptr
会将所有权从源指针移至目标指针(源
指针被置空)。
std::unique_ptr
不允许复制,因为如果复制了一个
std::unique_
ptr
,就会得到两个指涉到同一资源的
std::unique_ptr
,而这两者都认为自己拥有(因
此应当析构)该资源。因而,
std::unique_ptr
是个只移型别。在执行析构操作时,
由非空的
std::unique_ptr
析构其资源。默认地,资源的析构是通过对
std::unique_
ptr
内部的裸指针实施
delete
完成的。
std::unique_ptr
的一个常见用法是在对象继承谱系中作为工厂函数的返回型别。假设
我们有一个以
Investment
基类的投资型别的继承谱系(例如股票、债券、不动产等)。
class Investment ...
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

流畅的Python(第2版)

流畅的Python(第2版)

Luciano Ramalho
Go语言编程

Go语言编程

威廉·肯尼迪

Publisher Resources

ISBN: 9787519817749