SlideShare a Scribd company logo
1 of 44
Download to read offline
Modern C++ for Beginners
Kangjun Heo
November 5, 2019
ARGOS, Chungnam National University
Kangjun Heo, Modern C++ for Beginners 1/44
Presenter
• Kangjun Heo
• 17’ Computer Science and Engineering
• Chugnam National University since 2019
• ARGOS since 2019 spring semester
• knowledge@o.cnu.ac.kr / GitHub @0x00000FF
Kangjun Heo, Modern C++ for Beginners 2/44
Target Audiences
I recommend this presentation for these people...
• I am going to take Object Oriented Design
• I know C, going to use C++
• I am using C++ but going to use modern C++
Then I strongly recommend to listen this session!
Kangjun Heo, Modern C++ for Beginners 3/44
Contents
We’re going to see about:
• New keywords(constexpr, nullptr, auto)
• R-value Reference, Move semantics
• Smart Pointers
• ...and Lamba Expressions!
Kangjun Heo, Modern C++ for Beginners 4/44
Disclaimer
These slides contain very Basic informations of Modern C++!
Modern C++ has a lot of features than you thought...
Kangjun Heo, Modern C++ for Beginners 5/44
Modern C++
Kangjun Heo, Modern C++ for Beginners 6/44
Getting Started
For g++(gcc) users...
• g++ -std=c++11 example.cpp
For clang users...
• clang -std=c++11 exmaple.cpp
You can use c++14 or c++17 as an argument.
Kangjun Heo, Modern C++ for Beginners 7/44
Getting Started
For Visual Studio users...
• Properties - C/C++ - Language
Kangjun Heo, Modern C++ for Beginners 8/44
auto
C has a keyword auto
• It means ”local scoped variable”
• you can use it like this: auto a = 3;
• this is auto int equivalent
However...
• C++ 98 abandoned such syntax
• Also, C99 Abanoned it
• But Modern C++ picked it from the graveyard
Kangjun Heo, Modern C++ for Beginners 9/44
auto
In modern C++, auto is compile-time type deduction
auto a = 3; // a is int
auto fun() { // fun returns const char*
return "helloc";
}
Kangjun Heo, Modern C++ for Beginners 10/44
nullptr
Remember NULL? It’s a constant that is from C, equals 0...
• In strict, it’s not a null pointer but integer!
#define NULL 0
Kangjun Heo, Modern C++ for Beginners 11/44
nullptr
Kangjun Heo, Modern C++ for Beginners 12/44
nullptr
So, a new keyword nullptr and its type nullptr_t
appeared...
int* pIntVar = nullptr;
Kangjun Heo, Modern C++ for Beginners 13/44
nullptr
So, a new keyword nullptr and its type nullptr_t
appeared...
if ( pIntVar == nullptr )
Kangjun Heo, Modern C++ for Beginners 14/44
constexpr
In the beginning, C’s const exists...
const int a = 3; // constant?
int square(int num) {
int a = 3, b = 2;
const int ab = a + b;
return num * num;
}
Kangjun Heo, Modern C++ for Beginners 15/44
constexpr
square(int):
; skip
mov DWORD PTR [rbp-20], edi
mov DWORD PTR [rbp-4], 3
mov DWORD PTR [rbp-8], 2
mov edx, DWORD PTR [rbp-4]
mov eax, DWORD PTR [rbp-8]
add eax, edx
mov DWORD PTR [rbp-12], eax
; skip
Kangjun Heo, Modern C++ for Beginners 16/44
constexpr
• compile-time constant
• evaluated at compile-time
• functions, variables, objects...
Kangjun Heo, Modern C++ for Beginners 17/44
constexpr
int a = 3, b = 2;
constexpr int ab = a + b;
• err: the value of ’a’ is not usable in a constant expression
• only constexpr-able value or symbols are accepted
Kangjun Heo, Modern C++ for Beginners 18/44
constexpr
• Example: Factorial
constexpr int fac(int n)
{
return n > 0 ? n * fac(n-1) : 1;
}
int main()
{
int a = fac(4);
}
Kangjun Heo, Modern C++ for Beginners 19/44
constexpr
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 24
mov eax, 0
pop rbp
ret
Kangjun Heo, Modern C++ for Beginners 20/44
L-value vs R-value
L-Value(lhs) = R-Value(rhs)
• L-Value: A expression that have explicit memory space
• R-Value: Temporary Data or Object(e.g. Literals)
• Actually, R-Value is a complementary set of L-Value
Kangjun Heo, Modern C++ for Beginners 21/44
R-Value Reference
int a = 3;
int& b = a; // ok
int& c = 3; // not ok
int&& d = 3; // ok
Kangjun Heo, Modern C++ for Beginners 22/44
Move Semantics
SomeType a = SomeRValue;
// Calls SomeType::operator=(SomeType&)
• R-Value cannot be referenced
• Create and copy into new object to provide L-Value
Kangjun Heo, Modern C++ for Beginners 23/44
Move Semantics
SomeType a = std::move(SomeRValue);
// Calls SomeType::operator=(SomeType&&)
Kangjun Heo, Modern C++ for Beginners 24/44
Pop Quiz
How many methods this class have in Modern C++?
class A { };
Hint In legacy C++, there were 4 methods in empty class.
Kangjun Heo, Modern C++ for Beginners 25/44
Pop Quiz
Answer: 6
class A {
public:
A();
A(const A&);
A& operator=(const A&);
~A();
A(A&&) noexcept;
A& operator=(A&&) noexcept;
};
Kangjun Heo, Modern C++ for Beginners 26/44
RAII & Ownership
Resource Acquisition Is Initialization
• Resource acquisition must be done when initialized
• Every valid objects must acquire necessary resources
• Object that required resources are not valid
Kangjun Heo, Modern C++ for Beginners 27/44
RAII & Ownership
Ownership
• So called Ownership Semantics
• Responsibility of the owner of a chunk of dynamically
allocated memory to release that memory.
Kangjun Heo, Modern C++ for Beginners 28/44
Smart Pointer
void fun() {
// acquired SomeType
const SomeType* somePtr = new SomeType;
// do something useful...
// somePtr is passed several subroutines
...
}
// fun() ended, but somePtr's not released
• Raw pointers are not ”Object”
• Address for SomeType Object can be shared with
unregulated manner
Kangjun Heo, Modern C++ for Beginners 29/44
Smart Pointer
Smart Pointers are declared in STL header <memory>
• std::unique_ptr<T>
• std::shared_ptr<T>
• std::weak_ptr<T>
Kangjun Heo, Modern C++ for Beginners 30/44
std::unique_ptr<T>
• Only one unique_ptr can own a resource.
• Resource is automatically released once unique_ptr is
destroyed.
auto uPtr =
new std::unique_ptr<SomeType>(
new SomeType()
); // C++ 11
auto uPtr =
std::make_unique<SomeType>(); // C++ 14
Kangjun Heo, Modern C++ for Beginners 31/44
std::shared_ptr<T>
• One or more shared_ptr can own a resource.
• It has ’Reference counter’, indicates how many
shared_ptrs are having onwership.
• Once Reference counter reaches 0, the resource will be
released.
auto sPtr =
new std::shared_ptr<SomeType>(
new SomeType()
); // C++ 11
auto sPtr =
std::make_shared<SomeType>(); // C++ 14
Kangjun Heo, Modern C++ for Beginners 32/44
std::weak_ptr<T>
• Has no ownership for the resources
• Don’t affect reference counter
• Provides some observation methods
Kangjun Heo, Modern C++ for Beginners 33/44
std::weak_ptr<T>
auto sp = std::make_shared<SType>();
std::weak_ptr<SType> wp = sp;
if (auto sp2 = wp.lock()) { // get from wp
// do with sp2 is not nullptr
}
if (!wp.expired()) { // check if deleted
// do something when sp is not expired
}
Kangjun Heo, Modern C++ for Beginners 34/44
Lambda Expressions
Lambda is a unnamed function object.
[capture] (args) -> returnType {
//body
}
Kangjun Heo, Modern C++ for Beginners 35/44
Lambda Expressions
Lambda Capture
• & means capture by-reference.
• = means capture by-copy. -> default
[] () { } // capture default (this)
[=] () { } // capture by-copy default (same)
[=, &r] () { } // copy all, but r is by-ref
[&] () { } // by-ref default
[&, c] ( ) { } // ref all, but c is by-copy
Kangjun Heo, Modern C++ for Beginners 36/44
Lambda Expressions
[] { std::cout << "hi"; }(); //just call
// c is std::vector
std::for_each(c.begin(), c.end(),
[](auto& item) {
// do for_each loop callbacks
}); // pass as argument
Kangjun Heo, Modern C++ for Beginners 37/44
Summary
From Modern C++, we got a bunch of useful features:
• auto, nullptr, constexpr
• R-Value Reference, Move Semantics
• Smart pointers
• Lambda Expressions
Kangjun Heo, Modern C++ for Beginners 38/44
Recommended Sites
For the references of C++ standard...
• cppreference (https://en.cppreference.com/)
And several C++ implmentations...
• GCC libstdc++ (https://github.com/gcc-mirror/gcc)
• Clang libcxx (https://github.com/llvm-mirror/libcxx)
• Microsoft STL (https://github.com/microsoft/STL)
Kangjun Heo, Modern C++ for Beginners 39/44
Recommended Books
• Effective Modern C++
Kangjun Heo, Modern C++ for Beginners 40/44
Recommended Books
• Discovering Modern C++
Kangjun Heo, Modern C++ for Beginners 41/44
Communities
C++ Korea (https://www.facebook.com/groups/cppkorea/)
Kangjun Heo, Modern C++ for Beginners 42/44
Q&A
Kangjun Heo, Modern C++ for Beginners 43/44
Tank you so march!
...And these slides were made with LATEX!
Kangjun Heo, Modern C++ for Beginners 44/44

More Related Content

What's hot

Shared Memory Parallelism with Python by Dr.-Ing Mike Muller
Shared Memory Parallelism with Python by Dr.-Ing Mike MullerShared Memory Parallelism with Python by Dr.-Ing Mike Muller
Shared Memory Parallelism with Python by Dr.-Ing Mike MullerPyData
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++kinan keshkeh
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guideTiago Faller
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, iohtaitk
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1IIUM
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1IIUM
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
Towards an SMT-based approach for Quantitative Information Flow
Towards an SMT-based approach for Quantitative Information FlowTowards an SMT-based approach for Quantitative Information Flow
Towards an SMT-based approach for Quantitative Information FlowQuoc-Sang Phan
 
Introduction to python programming [part 1]
Introduction to python programming [part 1]Introduction to python programming [part 1]
Introduction to python programming [part 1]Akhil Nadh PC
 
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
 
COSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in JuliaCOSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in Julia岳華 杜
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우Seok-joon Yun
 
talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013ericupnorth
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)Olve Maudal
 
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)Shinya Takamaeda-Y
 
Integrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBufIntegrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBufRomain Francois
 

What's hot (19)

Shared Memory Parallelism with Python by Dr.-Ing Mike Muller
Shared Memory Parallelism with Python by Dr.-Ing Mike MullerShared Memory Parallelism with Python by Dr.-Ing Mike Muller
Shared Memory Parallelism with Python by Dr.-Ing Mike Muller
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guide
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Towards an SMT-based approach for Quantitative Information Flow
Towards an SMT-based approach for Quantitative Information FlowTowards an SMT-based approach for Quantitative Information Flow
Towards an SMT-based approach for Quantitative Information Flow
 
Introduction to python programming [part 1]
Introduction to python programming [part 1]Introduction to python programming [part 1]
Introduction to python programming [part 1]
 
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...
 
COSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in JuliaCOSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in Julia
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
 
talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)
 
Yacf
YacfYacf
Yacf
 
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
Veriloggen.Stream: データフローからハードウェアを作る(2018年3月3日 高位合成友の会 第5回 @東京工業大学)
 
Integrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBufIntegrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBuf
 

Similar to Modern C++ for Beginners

Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeAkira Takahashi
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
C++: a fast tour of a fast language
C++: a fast tour of a fast languageC++: a fast tour of a fast language
C++: a fast tour of a fast languageAdrian Ostrowski
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective csagaroceanic11
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
 
PL-4048, Adapting languages for parallel processing on GPUs, by Neil Henning
PL-4048, Adapting languages for parallel processing on GPUs, by Neil HenningPL-4048, Adapting languages for parallel processing on GPUs, by Neil Henning
PL-4048, Adapting languages for parallel processing on GPUs, by Neil HenningAMD Developer Central
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Kenneth Geisshirt
 
Python image processing_Python image processing.pptx
Python image processing_Python image processing.pptxPython image processing_Python image processing.pptx
Python image processing_Python image processing.pptxshashikant484397
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
 
C++14 - Modern Programming for Demanding Times
C++14 - Modern Programming for Demanding TimesC++14 - Modern Programming for Demanding Times
C++14 - Modern Programming for Demanding TimesCarlos Miguel Ferreira
 
C++11 Was Only the Beginning
C++11 Was Only the BeginningC++11 Was Only the Beginning
C++11 Was Only the BeginningMateusz Pusz
 
High-Performance Python
High-Performance PythonHigh-Performance Python
High-Performance PythonWork-Bench
 

Similar to Modern C++ for Beginners (20)

Replace OutputIterator and Extend Range
Replace OutputIterator and Extend RangeReplace OutputIterator and Extend Range
Replace OutputIterator and Extend Range
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Return of c++
Return of c++Return of c++
Return of c++
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
C++: a fast tour of a fast language
C++: a fast tour of a fast languageC++: a fast tour of a fast language
C++: a fast tour of a fast language
 
C
CC
C
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
PL-4048, Adapting languages for parallel processing on GPUs, by Neil Henning
PL-4048, Adapting languages for parallel processing on GPUs, by Neil HenningPL-4048, Adapting languages for parallel processing on GPUs, by Neil Henning
PL-4048, Adapting languages for parallel processing on GPUs, by Neil Henning
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
Python image processing_Python image processing.pptx
Python image processing_Python image processing.pptxPython image processing_Python image processing.pptx
Python image processing_Python image processing.pptx
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
Modern C++
Modern C++Modern C++
Modern C++
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
C++14 - Modern Programming for Demanding Times
C++14 - Modern Programming for Demanding TimesC++14 - Modern Programming for Demanding Times
C++14 - Modern Programming for Demanding Times
 
C++11 Was Only the Beginning
C++11 Was Only the BeginningC++11 Was Only the Beginning
C++11 Was Only the Beginning
 
High-Performance Python
High-Performance PythonHigh-Performance Python
High-Performance Python
 

Recently uploaded

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Recently uploaded (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Modern C++ for Beginners

  • 1. Modern C++ for Beginners Kangjun Heo November 5, 2019 ARGOS, Chungnam National University Kangjun Heo, Modern C++ for Beginners 1/44
  • 2. Presenter • Kangjun Heo • 17’ Computer Science and Engineering • Chugnam National University since 2019 • ARGOS since 2019 spring semester • knowledge@o.cnu.ac.kr / GitHub @0x00000FF Kangjun Heo, Modern C++ for Beginners 2/44
  • 3. Target Audiences I recommend this presentation for these people... • I am going to take Object Oriented Design • I know C, going to use C++ • I am using C++ but going to use modern C++ Then I strongly recommend to listen this session! Kangjun Heo, Modern C++ for Beginners 3/44
  • 4. Contents We’re going to see about: • New keywords(constexpr, nullptr, auto) • R-value Reference, Move semantics • Smart Pointers • ...and Lamba Expressions! Kangjun Heo, Modern C++ for Beginners 4/44
  • 5. Disclaimer These slides contain very Basic informations of Modern C++! Modern C++ has a lot of features than you thought... Kangjun Heo, Modern C++ for Beginners 5/44
  • 6. Modern C++ Kangjun Heo, Modern C++ for Beginners 6/44
  • 7. Getting Started For g++(gcc) users... • g++ -std=c++11 example.cpp For clang users... • clang -std=c++11 exmaple.cpp You can use c++14 or c++17 as an argument. Kangjun Heo, Modern C++ for Beginners 7/44
  • 8. Getting Started For Visual Studio users... • Properties - C/C++ - Language Kangjun Heo, Modern C++ for Beginners 8/44
  • 9. auto C has a keyword auto • It means ”local scoped variable” • you can use it like this: auto a = 3; • this is auto int equivalent However... • C++ 98 abandoned such syntax • Also, C99 Abanoned it • But Modern C++ picked it from the graveyard Kangjun Heo, Modern C++ for Beginners 9/44
  • 10. auto In modern C++, auto is compile-time type deduction auto a = 3; // a is int auto fun() { // fun returns const char* return "helloc"; } Kangjun Heo, Modern C++ for Beginners 10/44
  • 11. nullptr Remember NULL? It’s a constant that is from C, equals 0... • In strict, it’s not a null pointer but integer! #define NULL 0 Kangjun Heo, Modern C++ for Beginners 11/44
  • 12. nullptr Kangjun Heo, Modern C++ for Beginners 12/44
  • 13. nullptr So, a new keyword nullptr and its type nullptr_t appeared... int* pIntVar = nullptr; Kangjun Heo, Modern C++ for Beginners 13/44
  • 14. nullptr So, a new keyword nullptr and its type nullptr_t appeared... if ( pIntVar == nullptr ) Kangjun Heo, Modern C++ for Beginners 14/44
  • 15. constexpr In the beginning, C’s const exists... const int a = 3; // constant? int square(int num) { int a = 3, b = 2; const int ab = a + b; return num * num; } Kangjun Heo, Modern C++ for Beginners 15/44
  • 16. constexpr square(int): ; skip mov DWORD PTR [rbp-20], edi mov DWORD PTR [rbp-4], 3 mov DWORD PTR [rbp-8], 2 mov edx, DWORD PTR [rbp-4] mov eax, DWORD PTR [rbp-8] add eax, edx mov DWORD PTR [rbp-12], eax ; skip Kangjun Heo, Modern C++ for Beginners 16/44
  • 17. constexpr • compile-time constant • evaluated at compile-time • functions, variables, objects... Kangjun Heo, Modern C++ for Beginners 17/44
  • 18. constexpr int a = 3, b = 2; constexpr int ab = a + b; • err: the value of ’a’ is not usable in a constant expression • only constexpr-able value or symbols are accepted Kangjun Heo, Modern C++ for Beginners 18/44
  • 19. constexpr • Example: Factorial constexpr int fac(int n) { return n > 0 ? n * fac(n-1) : 1; } int main() { int a = fac(4); } Kangjun Heo, Modern C++ for Beginners 19/44
  • 20. constexpr main: push rbp mov rbp, rsp mov DWORD PTR [rbp-4], 24 mov eax, 0 pop rbp ret Kangjun Heo, Modern C++ for Beginners 20/44
  • 21. L-value vs R-value L-Value(lhs) = R-Value(rhs) • L-Value: A expression that have explicit memory space • R-Value: Temporary Data or Object(e.g. Literals) • Actually, R-Value is a complementary set of L-Value Kangjun Heo, Modern C++ for Beginners 21/44
  • 22. R-Value Reference int a = 3; int& b = a; // ok int& c = 3; // not ok int&& d = 3; // ok Kangjun Heo, Modern C++ for Beginners 22/44
  • 23. Move Semantics SomeType a = SomeRValue; // Calls SomeType::operator=(SomeType&) • R-Value cannot be referenced • Create and copy into new object to provide L-Value Kangjun Heo, Modern C++ for Beginners 23/44
  • 24. Move Semantics SomeType a = std::move(SomeRValue); // Calls SomeType::operator=(SomeType&&) Kangjun Heo, Modern C++ for Beginners 24/44
  • 25. Pop Quiz How many methods this class have in Modern C++? class A { }; Hint In legacy C++, there were 4 methods in empty class. Kangjun Heo, Modern C++ for Beginners 25/44
  • 26. Pop Quiz Answer: 6 class A { public: A(); A(const A&); A& operator=(const A&); ~A(); A(A&&) noexcept; A& operator=(A&&) noexcept; }; Kangjun Heo, Modern C++ for Beginners 26/44
  • 27. RAII & Ownership Resource Acquisition Is Initialization • Resource acquisition must be done when initialized • Every valid objects must acquire necessary resources • Object that required resources are not valid Kangjun Heo, Modern C++ for Beginners 27/44
  • 28. RAII & Ownership Ownership • So called Ownership Semantics • Responsibility of the owner of a chunk of dynamically allocated memory to release that memory. Kangjun Heo, Modern C++ for Beginners 28/44
  • 29. Smart Pointer void fun() { // acquired SomeType const SomeType* somePtr = new SomeType; // do something useful... // somePtr is passed several subroutines ... } // fun() ended, but somePtr's not released • Raw pointers are not ”Object” • Address for SomeType Object can be shared with unregulated manner Kangjun Heo, Modern C++ for Beginners 29/44
  • 30. Smart Pointer Smart Pointers are declared in STL header <memory> • std::unique_ptr<T> • std::shared_ptr<T> • std::weak_ptr<T> Kangjun Heo, Modern C++ for Beginners 30/44
  • 31. std::unique_ptr<T> • Only one unique_ptr can own a resource. • Resource is automatically released once unique_ptr is destroyed. auto uPtr = new std::unique_ptr<SomeType>( new SomeType() ); // C++ 11 auto uPtr = std::make_unique<SomeType>(); // C++ 14 Kangjun Heo, Modern C++ for Beginners 31/44
  • 32. std::shared_ptr<T> • One or more shared_ptr can own a resource. • It has ’Reference counter’, indicates how many shared_ptrs are having onwership. • Once Reference counter reaches 0, the resource will be released. auto sPtr = new std::shared_ptr<SomeType>( new SomeType() ); // C++ 11 auto sPtr = std::make_shared<SomeType>(); // C++ 14 Kangjun Heo, Modern C++ for Beginners 32/44
  • 33. std::weak_ptr<T> • Has no ownership for the resources • Don’t affect reference counter • Provides some observation methods Kangjun Heo, Modern C++ for Beginners 33/44
  • 34. std::weak_ptr<T> auto sp = std::make_shared<SType>(); std::weak_ptr<SType> wp = sp; if (auto sp2 = wp.lock()) { // get from wp // do with sp2 is not nullptr } if (!wp.expired()) { // check if deleted // do something when sp is not expired } Kangjun Heo, Modern C++ for Beginners 34/44
  • 35. Lambda Expressions Lambda is a unnamed function object. [capture] (args) -> returnType { //body } Kangjun Heo, Modern C++ for Beginners 35/44
  • 36. Lambda Expressions Lambda Capture • & means capture by-reference. • = means capture by-copy. -> default [] () { } // capture default (this) [=] () { } // capture by-copy default (same) [=, &r] () { } // copy all, but r is by-ref [&] () { } // by-ref default [&, c] ( ) { } // ref all, but c is by-copy Kangjun Heo, Modern C++ for Beginners 36/44
  • 37. Lambda Expressions [] { std::cout << "hi"; }(); //just call // c is std::vector std::for_each(c.begin(), c.end(), [](auto& item) { // do for_each loop callbacks }); // pass as argument Kangjun Heo, Modern C++ for Beginners 37/44
  • 38. Summary From Modern C++, we got a bunch of useful features: • auto, nullptr, constexpr • R-Value Reference, Move Semantics • Smart pointers • Lambda Expressions Kangjun Heo, Modern C++ for Beginners 38/44
  • 39. Recommended Sites For the references of C++ standard... • cppreference (https://en.cppreference.com/) And several C++ implmentations... • GCC libstdc++ (https://github.com/gcc-mirror/gcc) • Clang libcxx (https://github.com/llvm-mirror/libcxx) • Microsoft STL (https://github.com/microsoft/STL) Kangjun Heo, Modern C++ for Beginners 39/44
  • 40. Recommended Books • Effective Modern C++ Kangjun Heo, Modern C++ for Beginners 40/44
  • 41. Recommended Books • Discovering Modern C++ Kangjun Heo, Modern C++ for Beginners 41/44
  • 43. Q&A Kangjun Heo, Modern C++ for Beginners 43/44
  • 44. Tank you so march! ...And these slides were made with LATEX! Kangjun Heo, Modern C++ for Beginners 44/44