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版)

8.6 计算顺序

一个程序的计算或称为程序的执行,就是按照语言的规则逐条运行程序中的语句。当这个“执行线程”到达一个变量定义时,变量就会被创建,也就是说编译器会为它分配内存空间,并对其进行初始化。当变量退出其作用域时,将会被销毁,即,原则上它指向的对象会被删除,编译器可把它原来占用的内存作他用。例如:

像program_name和v这样的全局变量,在main()的第一条语句执行之前就会被初始化。其生存期直至程序结束,随后会被销毁。它们创建的顺序与定义的顺序相符(program_name先于v创建),而销毁则按相反的次序(v先于program_name销毁)。

当有代码调用f()时,首先会创建s,并将其初始化为空字符串,s的生命期会持续到从f()返回的时刻。

每次进入while循环的循环体时,stripped和not_letters两个变量会被创建。由于stripped先于not_letters定义,因此它也先被创建。两个变量的生存期都是到本次循环步的结束为止,在循环条件重新求值之前被销毁,销毁顺序与创建顺序相反(也就是说not_letters先于stripped被销毁)。因此,如果我们在遇到字符串“quit”之前读入10个其他的字符串,stripped和not_letters将会被创建和销毁10次。

每次到达for循环时,i会被创建。每次退出for循环时,到达语句v.push_back(stripped);前,i会被销毁。

请注意,编译器是聪明的家伙,它们获准优化代码,只要得到的结果与我们的目的相符即可。特别是,编译器在分配/释放内存方面很聪明,不会不必要地频繁分配/释放内存。 ...

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