Movatterモバイル変換


[0]ホーム

URL:


ModernC++
Programming
1.Introduction
FedericoBusato
2025-04-14
TableofContents
1ALittleHistoryofC/C++ProgrammingLanguage
2AreasofApplicationandPopularity
3C++Philosophy
4C++Weaknesses
C++Alternatives
WhySwitchingtoaNewLanguageisHard?
5TheCourse
1/55
AboutMotivation1/5
“Whenrecruitingresearchassistants,Ilookatgradesasthelastindi-
cator.Ifindthatimagination,ambition,initiative,curiosity,drive,
arefarbetterpredictorsofsomeonewhowilldousefulworkwithme.Of
course,thesecharacteristicsarethemselvescorrelatedwithhighgrades,
butthereissomethingtobesaidaboutastudentwhodecidesthata
givencourseisawasteoftimeandthatheworksonasideprojectin-
stead.
Breakthroughsdon’thappeninregularscheduledclasses,theyhappen
insideprojects.Wewantpeoplewhocompletetheworktheywereas-
signed,butwealsoneedpeoplewhocanreflectcriticallyonwhat
isgenuinelyimportant"
DanielLemire,Prof.attheUniversityofQuebec
2/55
AboutMotivation2/5
Academicexcellenceisnotastrongpredictor
ofcareerexcellence
“Acrossindustries,researchshowsthatthecorrelationbetweengrades
andjobperformanceismodestinthefirstyearaftercollegeandtrivial
withinahandfulofyears...
Academicgradesrarelyassessqualitieslikecreativity,leadershipandteam-
workskills,orsocial,emotionalandpoliticalintelligence.Yes,straight-A
studentsmastercramminginformationandregurgitatingitonexams.
Butcareersuccessisrarelyaboutfindingtherightsolutiontoa
problemit’smoreaboutfindingtherightproblemtosolve...
3/55
AboutMotivation3/5
“GettingstraightA’srequiresconformity.Havinganinfluential
careerdemandsoriginality.
ThismightexplainwhySteveJobsfinishedhighschoolwitha2.65
G.P.A.,J.K.RowlinggraduatedfromtheUniversityofExeterwith
roughlyaCaverage,andtheRev.Dr.MartinLutherKingJr.gotonly
oneAinhisfouryearsatMorehouse
Ifyourgoalistograduatewithoutablemishonyourtranscript,you
enduptakingeasierclassesandstayingwithinyourcomfortzone.If
you’rewillingtotoleratetheoccasionalB...Yougainexperiencecoping
withfailuresandsetbacks,whichbuildsresilience
4/55
AboutMotivation4/5
“Straight-Astudentsalsomissoutsocially.Moretimestudyingin
thelibrarymeanslesstimetostartlifelongfriendships,joinnewclubsor
volunteer...Lookingback,Idon’twishmygradeshadbeenhigher.IfI
coulddoitoveragain,I’dstudyless”
AdamGrant,theNewYorkTimes
www.nytimes.com/2018/12/08/opinion/college-gpa-career-success.html
5/55
AboutMotivation5/5
“Gota2.4GPAmyfirstsemesterincollege.ThoughtmaybeIwasn’t
cutoutforengineering.TodayI’velandingtwospacecraftonMars,and
designingoneforthemoon.
STEMishardforeveryone.Gradesultimatelyaren’twhatmatters.
Curiosityandpersistencematter
BenCichy,ChiefSoftwareEngineer,
NASAMarsScienceLaboratory
twitter.com/bencichy/status/1197752802929364992?s=20
6/55
AboutProgramming1/2
“Andprogrammingcomputerswassofascinating.Youcreateyour
ownlittleuniverse,andthenitdoeswhatyoutellittodo”
VintCerf,TCP/IPco-inventorandTuringAward
“Mostgoodprogrammersdoprogrammingnotbecausetheyexpectto
getpaidorgetadulationbythepublic,butbecauseitisfuntoprogram”
LinusTorvalds,principaldeveloperoftheLinuxkernel
“Youmightnotthinkthatprogrammersareartists,butprogramming
isanextremelycreativeprofession.It’slogic-basedcreativity”
JohnRomero,co-founderofidSoftware
7/55
AboutProgramming2/2
CreativityProgrammingisextremelycreative.Theabilitytoperceivetheproblemin
anovelway,providenewandoriginalsolutions.Creativityallows
recognizingandgeneratingalternatives
FormofArtArtistheexpressionofhumancreativeskills.Everyprogrammerhashis
ownstyle.Codesandalgorithmsshoweleganceandbeautyinthesame
wayaspaintingormusic
LearnProgramminggivestheopportunitytolearnnewthingseveryday,
improveownskillsandknowledge
ChallengeProgrammingisachallenge.Achallengeagainstyourself,theproblem,
andtheenvironment
8/55
Knowledge-ExperienceRelation
9/55
LearningandThinking
“Insoftwaredevelopment,learningisnotabigpartofthejob.
Itisthejob."
WoodyZuill
“Programmingisnotabouttyping,it’saboutthinking."
RichHickey
10/55
ALittleHistoryof
C/C++
Programming
Language
TheAssemblyProgrammingLanguage
Alongtimeago,inagalaxyfar,
faraway....therewasAssembly
Extremelysimpleinstructions
Requireslotsofcodetodosimpletasks
Canexpressanythingyourcomputercando
Hardtoread,write
...redundant,boringprogramming,bugspro-
liferation
main:
.Lfunc_begin0:
pushrbp
.Lcfi0:
.Lcfi1:
movrbp,rsp
.Lcfi2:
subrsp,16
movabsrdi,.L.str
.Ltmp0:
moval,0
callprintf
xorecx,ecx
movdwordptr[rbp-4],eax
moveax,ecx
addrsp,16
poprbp
ret
.Ltmp1:
.Lfunc_end0:
.L.str:
.asciz"HelloWorld\n"
11/55
ALittleHistoryofC1/3
Inthe1969DennisM.RitchieandKenThompson(AT&T,BellLabs)workedon
developinganoperatingsystemforalargecomputerthatcouldbeusedbyathousand
users.ThenewoperatingsystemwascalledUNIX
Thewholesystemwasstillwritteninassemblycode.BesidesassemblerandFortran,
UNIXalsohadaninterpreterfortheprogramminglanguageB.Ahigh-levellanguage
likeBmadeitpossibletowritemanypagesofcodetaskinjustafewlinesofcode.In
thiswaythecodecouldbeproducedmuchfasterthaninassembly
AdrawbackoftheBlanguagewasthatitdidnotknowdata-types(everythingwas
expressedinmachinewords).AnotherfunctionalitythattheBlanguagedidnotprovide
wastheuseof“structures”.ThelackofthesethingsformedthereasonforDennis
M.RitchietodeveloptheprogramminglanguageC.In1988theydeliveredthefinal
standarddefinitionANSIC
12/55
ALittleHistoryofC2/3
DennisM.RitchieandKenThompson
#include"stdio.h"
intmain(){
printf("HelloWorld\n");
}
13/55
ALittleHistoryofC3/3
AreasofApplication:
UNIXoperatingsystem
Computergames
Duetotheirpowerandeaseofuse,Cwereusedintheprogrammingofthe
specialeffectsforStarWars
StarWars-TheEmpireStrikesBack
14/55
ALittleHistoryofC++1/3
TheC++programminglanguage(originallynamed“CwithClasses")wasdevised
byBjarneStroustrupalsoanemployeefromBellLabs(AT&T).Stroustrupstarted
workingonCwithClassesin1979.(The++isClanguageoperator)
ThefirstcommercialreleaseoftheC++languagewasinOctober1985
15/55
ALittleHistoryofC++2/3
TherootsofC++
TheEvolutionofC++Past,Present,andFuture”,B.Stroustrup,CppCon16
16/55
ALittleHistoryofC++3/3
17/55
AboutEvolution
“Ifyou’reteachingtodaywhatyouwereteachingfive
yearsago,eitherthefieldisdeadoryouare”
NoamChomsky
18/55
AreasofApplication
andPopularity
MostPopularProgrammingLanguages
(IEEESpectrum-2024)
Interactive:TheTopProgrammingLanguages2024
19/55
MostPopularProgrammingLanguages(TIOBE-October.2024)
www.tiobe.com/tiobe-index/
20/55
MostPopularProgrammingLanguages(Redmonk-June,2021)
redmonk.com
21/55
WhyC++issoPopular?1/2
Theremaybemorethan200billionlines
ofC/C++codeglobally
PerformanceisthedefiningaspectofC++.Nootherprogramming
languageprovidestheperformance-criticalfacilitiesofC++
Providetheprogrammercontrolovereveryaspectofperformance
Leavenoroomforalowerlevellanguage
Totalnumberoflinesofallcodeinuse?
22/55
WhyC++issoPopular?2/2
Ubiquity.C++canrunfromalow-powerembeddeddevicetolarge-scale
supercomputers
Multi-Paradigm.Allowwritingefficientcodewithoutlosinghigh-level
abstraction
Allowwritinglow-levelcode.Drivers,kernels,assembly(asm),etc.
Ecosystem.Manysupporttoolssuchasdebuggers,memorycheckers,
coverage,staticanalysis,profiling,etc.
Maturity.C++hasa40yearshistory.Manysoftwareproblemshavebeen
alreadyaddressedanddevelopingpracticeshavebeeninvestigated
23/55
AreasofApplication1/2
Operatingsystems:Windows,Android,OSX,Linux
Compilers:LLVM,Swiftcompiler
ArtificialIntelligence:TensorFlow,Caffe,MicrosoftCognitiveToolkit
ImageEditing:AdobePremier,Photoshop,Illustrator
Webbrowser:Firefox,Chrome,etc.+WebAssembly
High-PerformanceComputing:drugdevelopingandtesting,largescaleclimate
models,physicsimulations
Embeddedsystems:IoT,networkdevices(e.g.GSM),automotive
GoogleandMicrosoftuseC++forwebindexing
24/55
AreasofApplication2/2
ScientificComputing:CERN/NASA*,SETI@home,Folding@home
Database:MySQL,ScyllaDB
VideoGames:UnrealEngine,Unity
Entertainment:Movierendering(seeInterstellarblackholerendering),
virtualreality
Finance:electronictradingsystems(Goldman,JPMorgan,DeutscheBank)**
...andmanymore
*TheflightcodeoftheNASAMarsdroneforthePerseveranceMission,aswellastheWebb
telescopesoftware,aremostlywritteninC++github.com/nasa/fprime,JamesWebbSpace
Telescope’sFullDeployment
**C++isthenewPython
25/55
WhyC++issoImportant?
TheEndofHistoricalPerformanceScaling
Performancelimitationsinfluencealgorithmdesign
andresearchdirections
26/55
AnImportantExample...(AIEvolution)
TheMoore’sLawis1.4xperyear
NotableAIModels
27/55
Performance1/4
8.23
21.47
21.9622.1
26.61
300
360
660
780
0
100
200
300
400
500
600
700
800
900
C++GOSWIFTJAVANode.jsPHPRubyPerlPython3
Execution TIme (S)
Programming Language
N-BODYSIMULATION
PROGRAMMINGLANGUAGESPERFORMANCECOMPARISON
28/55
Performance2/4
Aprogramminglanguagebenchmark
29/55
Performance3/4
”ANewGoldenAgeforComputerArchitecture“,J.L.Heneessey,D.A.Patterson,2019
30/55
Performance4/4
HelloWorld
LanguageExecutionTime
C(onmymachine)0.7ms
C2ms
Go4ms
Crystal8ms
Shell10ms
Python78ms
Node110ms
Ruby150ms
jRuby1.4s
Timeto"helloworld"onmymachine
31/55
Performance/ExpressivenessTrade-off
1
10
100
1,000
10,000
100,000
1,000,000
AssemblyCC++JavaJSPython
INSTRUCTIONS PER LINE
Mandelbrot Static Instructions per Line
32/55
MemoryUsage
Memoryusagecomparisonofthe
Neighbor-Joiningandglobalalignmentprograms
Acomparisonofcommonprogramminglanguagesusedinbioinformatics(BMC
Informatic)
33/55
EnergyEfficiency
EnergyEfficiencyacrossProgrammingLanguages
34/55
CO
2
Production
TheEcologicalImpactofHigh-performanceComputinginAstrophysics,Nature
35/55
C++Philosophy
C++Philosophy-Performance1/3
Donotsacrificeperformanceexceptasalastresort
ZeroOverheadPrinciple(zero-costabstraction)
“itbasicallysaysifyouhaveanabstractionitshouldnot
costanythingcomparedtowritetheequivalentcodeatlower
level”
“soIhavesayamatrixmultiplyitshouldbewrittenina
suchawaythatyoucouldnotdroptotheClevelofabstrac-
tionandusearraysandpointersandsuchandrunfaster”
BjarneStroustrup
36/55
C++Philosophy-TypeSafety2/3
Enforcesafetyatcompiletimewheneverpossible
StaticallyTypedLanguage
“TheC++compilerprovidestypesafetyandcatches
manybugsatcompiletimeinsteadofruntime(acritical
considerationformanycommercialapplications.)”
www.python.org/doc/FAQ.html
Thetypeannotationmakesthecodemorereadable
Promotecompileroptimizationsandruntimeefficiency
Allowuserstodefinetheirowntypesystem
37/55
C++Philosophy3/3
Programmingmodel:compartmentalization,onlyadd
featuresiftheysolveanactualproblem,andallowfullcontrol
Predictableruntime(underconstraints):nogarbage
collector,nodynamictypesystemreal-timesystems
Lowresources:lowmemoryandenergyconsumption
restrictedhardwareplatforms
Wellsuitedforstaticanalysissafetycriticalsoftware
PortabilityModernC++standardsarehighlyportable
38/55
WhoisC++for?
“C++isforpeoplewhowanttousehardwareverywell
andmanagethecomplexityofdoingthatthroughabstrac-
tion”
BjarneStroustrup
“alanguagelikeC++isnotforeverybody.Itisgener-
atedviasharpandeffectivetoolforprofessionalbasicallyand
definitelyforpeoplewhoaimatsomekindofprecision”
BjarneStroustrup
39/55
SuggestedIntroductionVideo
40/55
C++Weaknesses
WhyC++issoDifficult?1/2
...andwhyteachingC++asfirstprogramminglanguageisabadidea?
C++isthehardestlanguagefromstudentstomaster
Morelanguagesinone
-StandardC/C++programming
-Preprocessor
-Object-Orientedfeatures
-TemplatesandMeta-Programming
Hugesetoffeatures
Worryaboutmemorymanagement
Low-levelimplementationdetails:pointerarithmetic,structure,padding,
undefinedbehavior,etc.
Frustrating:compiler/runtimeerrors(e.g.seg.fault)
41/55
WhyC++issoDifficult?2/2
“Cmakesiteasytoshootyourselfinthefoot;C++makesitharder,
butwhenyoudo,itblowsyourwholelegoff
BjarneStroustrup,CreatoroftheC++language
“TheproblemwithusingC++...isthatthere’salreadyastrongten-
dencyinthelanguagetorequireyoutoknoweverythingbeforeyoucan
doanything”
LarryWall,CreatorofthePerllanguage
“Despitehaving20yearsofexperiencewithC++,whenIcompilea
non-trivialchunkofcodeforthefirsttimewithoutanyerrororwarning,
Iamsuspicious.Itisnot,usually,agoodsign”
DanielLemire,Prof.attheUniversityofQuebec
42/55
C++Weaknesses1/2
Backward-compatibility
‘Dangerousdefaultsandconstructs,oftenoriginatingfromC,cannotberemoved
oraltered”
“Despitethehardworkofthecommittee,newerfeaturessometimeshaveflaws
thatonlybecameobviousafterextensiveuserexperience,whichcannotthenbe
fixed”
“C++practicehasputanever-increasingcognitiveburdenonthedeveloperfor
whatIfeelhasbeenverylittlegaininproductivityorexpressivenessandatahugecost
tocodeclarity”
43/55
C++Weaknesses2/2
C++criticsandreplacements:
Epochs:abackward-compatiblelanguageevolutionmechanism
GoalsandprioritiesforC++
CarbonLanguage
CircleC++Compiler
Cppfront:CanC++be10xsimpler&safer...?
44/55
C++Alternatives:Rust
Rust(1.0,2015)hasbeenStackOverflow’smostlovedlanguageforeightyearsina
row.Rustfocusesonperformanceandzero-abstractionoverheadasC++.Itis
designedtopreventmanyvulnerabilitiesthataffectC++,especiallymemorybugs,
enforcingconstraintsatcompiletype.Inaddition,itpromotescross-platform
compatibility
“First-timecontributorstoRustprojectsareabout70timeslesslikelyto
introducevulnerabilitiesthanfirst-timecontributorstoC++projects”
Traceyetal.
1
1
GradingonaCurve:HowRustcanFacilitateNewContributorswhileDecreasing
Vulnerabilities
CISA,NSA:TheCaseforMemorySafeRoadmap
Octoverse:TheFastestGrowingLanguages
SecurebyDesign:Google’sPerspectiveonMemorySafety
45/55
C++Alternatives:Zig
Zig(2016)isaminimalopen-sourceprogramminglanguagethatcanbeintendedas
replacementofC.Zigsupportscompiletimegenerics,reflectionandevaluation,
cross-compiling,andmanualmemorymanagement.Itismadetobefullyinteroperable
withCandalsoincludesaC/C++compiler.
ZigProgrammingLanguage
46/55
WhySwitchingtoaNewLanguageisHard?1/3
Noperfectlanguage.Therearealwaysnewer’shining’languages
Alignment.Forcealldeveloperstoswitchtothenewlanguage
Interoperability.Hundredsofbillionlinesofexistingcode.Mustinteroperate
withCandC++codeimposingseriousdesignconstraints
Ecosystem.Lackoftoolsandlibrariesdevelopedinthelastfourdecades
TimeandCost.Convertingacodebaseof10millionlines:500developers,5
years,$1,400,000,000
1
1
BjarneStroustrup:DeliveringSafeC++
47/55
WhySwitchingtoaNewLanguageisHard?2/3
Performanceoverheadofsafeprogramminglanguages
TowardsUnderstandingtheRuntimePerformanceofRust
HowmuchdoesRust’sboundscheckingactuallycost?
HowtoavoidboundschecksinRust(withoutunsafe!)
IscodinginRustasbadasinC++?
48/55
WhySwitchingtoaNewLanguageisHard?3/3
49/55
LanguageComplexity
Everysecondspenttryingtounderstandthe
languageisonenotspentunderstandingthe
problem
50/55
TheCourse
TheCourse
51/55
TheCourse
Don’tforget:Therightnameofthecourseshouldbe
“IntroductiontoModernC++Programming”
Formanytopicsinthecourse,therearemorethanonebookdevotedtopresentthe
conceptsindetail
52/55
TheCourse
Theprimarygoalofthecourseistodrivewhohaspreviousexperiencewith
C/C++andobject-orientedprogrammingtoaproficiencylevelof(C++)
programming
Proficiency:knowwhatyouaredoingandtherelatedimplications
Understandwhatproblems/issuesaddressagivenlanguagefeature
Learnengineeringpractices(e.g.codeconventions,tools)andhardware/software
techniques(e.g.semantic,optimizations)thatarenotstrictlyrelatedtoC++
Whatthecourseis:
Apracticalcourse,preferexamplestolongdescriptions
A“quite”advancedC++programminglanguagecourse
Whatthecourseisnot:
Atheoreticalcourseonprogramming
Ahigh-levelconceptdescription
53/55
TheCourse
Organization:
26lectures
1,800slides
C++03/C++11/C++14/C++17/C++20/(C++23)/(C++26)
Roadmap:
ReviewCconceptsinC++(built-intypes,memorymanagement,preprocessing,
etc.)
Introduceobject-orientedandtemplateconcepts
Presenthowtoorganizethecodeandthemainconventions
C++toolgoalsandusage(debugger,staticanalysis,etc.)
54/55
WhoIAm
FedericoBusato,Ph.D.
federico-busato.github.io
SeniorSoftwareEngineeratNvidia,
CUDACoreComputeLibraries
FormerleadoftheSparseLinearAlgebragroup
Interests:
SparseLinearAlgebra
GraphAlgorithms
Parallel/High-PerformanceComputing
CodeOptimization
OnBluesky:fbusato.bsky
NOTaC++expert/“guru”,stilllearning
55/55
“WhatIcannotcreate,
Idonotunderstand"
RichardP.
Feynman
55/55
“Theonlywaytolearnanewpro-
gramminglanguageisbywritingpro-
gramsinit"
DennisRitchie
CreatoroftheCprogramminglanguage
55/55

[8]ページ先頭

©2009-2025 Movatter.jp