SlideShare a Scribd company logo
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

2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
htaitk
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
IIUM
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
IIUM
 

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

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
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
sagaroceanic11
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 

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 programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
C++11 Was Only the Beginning
C++11 Was Only the BeginningC++11 Was Only the Beginning
C++11 Was Only the Beginning
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

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