Slides from my presentation from GECon-2017 conference: https://events.epam.com/events/gecon-2017
It covers the following topics:
A bit of C++ evolution history.
Why C++ became popular and why C++ started to lose its popularity.
Why C++ is a Monster? If C ++ is a monster, then why does someone need C++?
How to use C++ safely and efficiently?
Where and when C++ can be used. If it can...
Pressure to C++ from competitors. Real and imaginary.
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
C++ это мультипарадигменный язык, поэтому программист сам может выбирать и совмещать структурный, объектно-ориентированный, обобщенный и функциональный подходы. Функциональный аспект C++ особенно расширился стандартом C++11: лямбда-функции, variadic templates, std::function, std::bind. (язык доклада: английский).
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
C++ это мультипарадигменный язык, поэтому программист сам может выбирать и совмещать структурный, объектно-ориентированный, обобщенный и функциональный подходы. Функциональный аспект C++ особенно расширился стандартом C++11: лямбда-функции, variadic templates, std::function, std::bind. (язык доклада: английский).
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
Once you know what a monad is, you start seeing them everywhere. The std::future library of C++11 was an example of an incomplete design, which stopped short of recognizing the monadic nature of futures. This is now being remedied in C++17, and there are new library additions, like std::expected and the range library, that are much more monad-conscious. I’ll explain what a monad is using copious C++ examples.
Presented by Stephen Murtagh, Etsy.com, Inc.
TF-IDF (term frequency, inverse document frequency) is a standard method of weighting query terms for scoring documents, and is the method that is used by default in Solr/Lucene. Unfortunately, TF-IDF is really only a measure of rarity, not quality or usefulness. This means it would give more weight to a useless, rare term, such as a misspelling, than to a more useful, but more common, term.
In this presentation, we will discuss our experiences replacing Lucene's TF-IDF based scoring function with a more useful one using information gain, a standard machine-learning measure that combines frequency and specificity. Information gain is much more expensive to compute, however, so this requires periodically computing the term weights outside of Solr/Lucene and making the results accessible within Solr/Lucene.
Razvan Rotari shows an experiment to see how far you can go with binding in C++; Cristian Neamtu follows with an insight on how to achieve this in Rust using Serde.
What's new with C++ since, oh, before the dot-com bubble? Learn more in this Lunch and Learn, with a refresher of C++ basics, C++/CLI for C# developers, and the new features of C++11/14 and possibly C++17.
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
To let the world know about our product, we check open-source projects. By the moment we have checked 245 projects. A side effect: we found 9574 errors and notified the authors about them.
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON
Many security critical systems rely on the correct implementation of the XML Digital Signature standard for the purposes of verification and identity management. Technologies such as SAML and Web Service Security use the standard, and its sibling XML Encryption, to manage the security of these technologies. Being a standard there is, unsurprisingly, no canonical implementation for any platform or language, with so many different developments there are likely to be differences in how the standard is interpreted.
This presentation is about research done against the main open and closed source implementations of XML Digital Signatures, how they can be exploited to gain remote code execution, signature verification bypass or denial of service. It will show some of the more nasty vulnerabilities found during the research including a novel attack against the built-in Java and .NET libraries which allow for trivial signature spoofing exposing any user of those implementations into accepting an invalid signature which is independent of their usage.
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element
array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
25 лет истории C++, пролетевшей на моих глазахcorehard_by
Автор доклада познакомился с C++ в 1991-ом году, а с 1992-го года C++ является для докладчика основным языком разработки. Что происходило с языком за это время? Как и почему он стал популярным? Как начался застой в развитии C++? Как C++ потерял свою популярность? Есть ли место для C++ в современном мире? Попробуем поговорить об этом опираясь на 25-летний опыт программирования на C++.
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
Once you know what a monad is, you start seeing them everywhere. The std::future library of C++11 was an example of an incomplete design, which stopped short of recognizing the monadic nature of futures. This is now being remedied in C++17, and there are new library additions, like std::expected and the range library, that are much more monad-conscious. I’ll explain what a monad is using copious C++ examples.
Presented by Stephen Murtagh, Etsy.com, Inc.
TF-IDF (term frequency, inverse document frequency) is a standard method of weighting query terms for scoring documents, and is the method that is used by default in Solr/Lucene. Unfortunately, TF-IDF is really only a measure of rarity, not quality or usefulness. This means it would give more weight to a useless, rare term, such as a misspelling, than to a more useful, but more common, term.
In this presentation, we will discuss our experiences replacing Lucene's TF-IDF based scoring function with a more useful one using information gain, a standard machine-learning measure that combines frequency and specificity. Information gain is much more expensive to compute, however, so this requires periodically computing the term weights outside of Solr/Lucene and making the results accessible within Solr/Lucene.
Razvan Rotari shows an experiment to see how far you can go with binding in C++; Cristian Neamtu follows with an insight on how to achieve this in Rust using Serde.
What's new with C++ since, oh, before the dot-com bubble? Learn more in this Lunch and Learn, with a refresher of C++ basics, C++/CLI for C# developers, and the new features of C++11/14 and possibly C++17.
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
To let the world know about our product, we check open-source projects. By the moment we have checked 245 projects. A side effect: we found 9574 errors and notified the authors about them.
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON
Many security critical systems rely on the correct implementation of the XML Digital Signature standard for the purposes of verification and identity management. Technologies such as SAML and Web Service Security use the standard, and its sibling XML Encryption, to manage the security of these technologies. Being a standard there is, unsurprisingly, no canonical implementation for any platform or language, with so many different developments there are likely to be differences in how the standard is interpreted.
This presentation is about research done against the main open and closed source implementations of XML Digital Signatures, how they can be exploited to gain remote code execution, signature verification bypass or denial of service. It will show some of the more nasty vulnerabilities found during the research including a novel attack against the built-in Java and .NET libraries which allow for trivial signature spoofing exposing any user of those implementations into accepting an invalid signature which is independent of their usage.
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element
array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
25 лет истории C++, пролетевшей на моих глазахcorehard_by
Автор доклада познакомился с C++ в 1991-ом году, а с 1992-го года C++ является для докладчика основным языком разработки. Что происходило с языком за это время? Как и почему он стал популярным? Как начался застой в развитии C++? Как C++ потерял свою популярность? Есть ли место для C++ в современном мире? Попробуем поговорить об этом опираясь на 25-летний опыт программирования на C++.
Computer Vision using Ruby and libJIT - RubyConf 2009Jan Wedekind
Ruby originated in Japan, the country which is world-leading in robotic research. It suggests itself to put the two together and to start using Ruby as a language to program robots. However at the moment the performance of available Ruby interpreters is not sufficient. It is hard to achieve performance comparable to compiled C++-code since manipulation of Ruby-integers and Ruby-arrays requires frequent bounds-checking. It can be shown that universal bounds-check elimination is actually impossible.
FITC events. For digital creators.
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
An Intro To ES6
with Grant Skinner
OVERVIEW
ECMAScript 6 is the approved and published standard for the next version of JavaScript. It offers new syntax and language features that provide new ways of tackling coding problems, and increase your productivity.
This session will introduce ES6 and delve into many of the new features of the language. It will also cover real-world use, including transpilers, runtimes, and browser support.
OBJECTIVE
Create confidence in evaluating and getting started using ES6.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
JavaScript.
FOUR THINGS AUDIENCE MEMBERS WILL LEARN
Status of ES6
How to get started with ES6
ES6 feature overview
Practical considerations for adopting ES6
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
arataga. SObjectizer and RESTinio in action: a real-world exampleYauheni Akhotnikau
Slides about the usage of SObjectizer and RESTinio in implementation of performant socks5/http1.1 proxy server that has to deal with thousands of entry points.
Actor Model and C++: what, why and how? (March 2020 Edition)Yauheni Akhotnikau
This is an updated version of slides from my talk on the C++ CoreHard Autumn 2016 conference.
The Actor Model which is currently trending in software development is a popular design approach when it comes to complex applications. Many systems are written in Erlang (Akka framework) are designed with the Actor Model in their core. But Erlang and Akka are managed environments and safe programming languages. Is it worth using the Actor Model in C++? If yes, where to look and what to use? The talk will cover all these topics.
Слайды одноименного доклада с конференции C++ CoreHard Autumn 2018 (г.Минск, 2018.11.03).
Краткое описание доклада:
На предыдущих конференциях C++ CoreHard автор доклада рассказывал про Модель Акторов и опыт ее использования в C++. Но Модель Акторов -- это далеко не единственный способ борьбы со сложностью при работе с многопоточностью. Давайте попробуем поговорить о том, что еще можно применить и как это может выглядеть в C++.
Shrimp: A Rather Practical Example Of Application Development With RESTinio a...Yauheni Akhotnikau
Description of a demo project for serving images by using Actor Model and embedded HTTP-server. This project is implemented in C++17 with SObjectizer and RESTinio (OpenSource products from stiffstream).
Акторы в C++: взгляд старого практикующего актородела (St. Petersburg C++ Use...Yauheni Akhotnikau
Автор доклада более 16 лет отвечает за развитие Open-Source фреймворка SObjectizer -- одного из немногих живых, эволюционирующих, кросс-платформенных фреймворков для C++, базирующихся на Модели Акторов. При этом SObjectizer никогда не был исследовательским экспериментом и с самого начала использовался в ряде business-critical проектов.
За годы разработки и эксплуатации SObjectizer накопился некоторый практический опыт использования акторов в С++, которым докладчик поделится со слушателями. Речь пойдет о том, почему Модель Акторов выглядит привлекательной, где и когда ее выгодно использовать. Какие особенности накладывает именно С++ и разумно ли использовать Модель Акторов в C++? Почему реализации Модели Акторов для C++ настолько разные и почему SObjectizer получился именно таким?
Слайды одноименного доклада с конференции "C++ Russia 2018". В докладе речь идет о том, насколько C++ мешает и насколько C++ помогает в разработке акторного фреймворка для C++.
Dive into SObjectizer 5.5. Tenth part: Mutable MessagesYauheni Akhotnikau
This part describes a feature which was introduced in v.5.5.19: an ability to send mutable messages with guarantees that it will be delivered to at most one receiver.
Actor model which is currently trending in software development is a popular design approach when it comes to complex applications. Many systems written in Erlang (Akka framework) are designed with actor model in their core. But Erlang and Akka are managed environments and safe programming languages. Is it worth using actor model in C++? If yes, where to look and what to use? The talk will cover all these topics.
Слайды доклада на конференции C++ Corehard Winter 2017 (г.Минск).
Автор доклада давно и успешно использует Модель Акторов при разработке приложений на C++. В основном это был положительный опыт. Но есть некоторые неочевидные моменты, про которые было бы хорошо узнать заранее. О том, где использование Модели Акторов уместно, а где нет, на какие грабли довелось наступить, какие шишки были набиты, как можно упростить себе жизнь и пойдет речь в докладе.
Dive into SObjectizer 5.5. Seventh part: Message LimitsYauheni Akhotnikau
Next part of serie with deep dive into SObjectizer-5.5. A brief explanation of message limits feature. This feature allows to protect agents from overloading in simple situations and can be used as building blocks for more complex and domain-specific overload control schemes.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Launch Your Streaming Platforms in MinutesRoshan Dwivedi
The claim of launching a streaming platform in minutes might be a bit of an exaggeration, but there are services that can significantly streamline the process. Here's a breakdown:
Pros of Speedy Streaming Platform Launch Services:
No coding required: These services often use drag-and-drop interfaces or pre-built templates, eliminating the need for programming knowledge.
Faster setup: Compared to building from scratch, these platforms can get you up and running much quicker.
All-in-one solutions: Many services offer features like content management systems (CMS), video players, and monetization tools, reducing the need for multiple integrations.
Things to Consider:
Limited customization: These platforms may offer less flexibility in design and functionality compared to custom-built solutions.
Scalability: As your audience grows, you might need to upgrade to a more robust platform or encounter limitations with the "quick launch" option.
Features: Carefully evaluate which features are included and if they meet your specific needs (e.g., live streaming, subscription options).
Examples of Services for Launching Streaming Platforms:
Muvi [muvi com]
Uscreen [usencreen tv]
Alternatives to Consider:
Existing Streaming platforms: Platforms like YouTube or Twitch might be suitable for basic streaming needs, though monetization options might be limited.
Custom Development: While more time-consuming, custom development offers the most control and flexibility for your platform.
Overall, launching a streaming platform in minutes might not be entirely realistic, but these services can significantly speed up the process compared to building from scratch. Carefully consider your needs and budget when choosing the best option for you.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
A Sighting of filterA in Typelevel Rite of Passage
GECon 2017: C++ - a Monster that no one likes but that will outlast them all
1. C++ ‒ a Monster
that no one likes
but that will outlast them all
Yauheni Akhotnikau
2. 2
Started programming somewhere in 1990.
The first meet with C++ in 1991.
C++ is the main tool since 1992 with a few short pauses.
Used some other languages. For example: Pascal, Visual Basic, Java, Ruby, D,
Eiffel, Scala.
I can use C++ without a pain but I don't think that C++ is the greatest
language ever.
A few words about me
3. 3
A bit of C++ evolution history.
Why C++ became popular and why C++ started to lose its popularity.
Why C++ is a Monster? If C ++ is a monster, then why does someone need
C++?
How to use C++ safely and efficiently?
Where and when C++ can be used. If it can...
Pressure to C++ from competitors. Real and imaginary.
Agenda
5. 5
By the help of a simple demo application:
• there is a collection of struct place (each struct contains name, price and rating);
• sort this collection by rating, then by price, then by name. And then print the collection after
sorting;
• sort this collection by name, then print it.
A way to see the evolution in examples
6. 6
Work on C++ began in 1979.
Bjarne Stroustrup decided to build a language with power of Simula 67 and
efficiency of C.
The first name of the new language was "C with Classes". Name C++
appeared in 1983.
The first public release in 1985.
The birth of C++
7. 7
struct place {
char * name_;
long price_;
int rating_;
place() : name_(0) {}
place(const char * name, long price, int rating)
: name_(copy_name(name)), price_(price), rating_(rating) {}
place(const place & o)
: name_(copy_name(o.name_)), price_(o.price_), rating_(o.rating_) {}
~place() { delete[] name_; }
place & operator=(const place & o) {
char * copy = copy_name(o.name_);
delete[] name_;
name_ = copy; price_ = o.price_; rating_ = o.rating_;
return *this;
}
static char * copy_name(const char * src) {
char * r = 0;
if(src) {
r = new char[strlen(src) + 1];
strcpy(r, src);
}
return r;
}
};
A taste of ancient C++ (pre-C++98)
8. 8
ostream & operator<<(ostream & to, const place & p) {
to << setw(20) << left << p.name_ << "[" << p.rating_ << "]"
<< setw(7) << right << p.price_;
return to;
}
void print(const place * places, size_t count) {
for(size_t i = 0; i != count; ++i)
cout << places[i] << endl;
cout << endl;
}
A taste of ancient C++ (pre-C++98)
9. 9
int compare_by_rating_price_name(const void * av, const void * bv) {
const place & a = *(const place *)av;
const place & b = *(const place *)bv;
int result;
if(a.rating_ < b.rating_) result = -1;
else {
if(a.rating_ == b.rating_) {
if(a.price_ < b.price_) result = -1;
else {
if(a.price_ == b.price_) {
result = strcmp(a.name_, b.name_);
}
else result = 1;
}
}
else result = 1;
}
return result;
}
int compare_by_name(const void * av, const void * bv) {
const place & a = *(const place *)av;
const place & b = *(const place *)bv;
return strcmp(a.name_, b.name_);
}
A taste of ancient C++ (pre-C++98)
11. 11
int main() {
place * places;
size_t count;
get_places(places, count);
qsort(places, count, sizeof(place), compare_by_rating_price_name);
print(places, count);
qsort(places, count, sizeof(place), compare_by_name);
print(places, count);
delete[] places;
}
A taste of ancient C++ (pre-C++98)
12. 12
Moscow [3] 1500
Sydney [3] 5000
Minsk [4] 500
London [4] 3500
Tokyo [4] 3500
St. Petersburg [5] 1300
Paris [5] 3000
London [4] 3500
Minsk [4] 500
Moscow [3] 1500
Paris [5] 3000
St. Petersburg [5] 1300
Sydney [3] 5000
Tokyo [4] 3500
A taste of ancient C++ (pre-C++98)
13. 13
1985-1995: fast evolution:
– multiple inheritance, const-methods, protected keyword, namespaces, templates, exceptions,
RTTI, explicit keyword, ...
1990: ANSI/ISO standardization started.
1992: Alex Stepanov started STL.
1994-1998: process of inclusion of STL into the standard.
1998: the first international standard ‒ C++98.
2003: an updated standard ‒ C++03.
1985-2003: main milestones
14. 14
using namespace std;
struct place {
string name_;
long price_;
int rating_;
place() {}
place(const char * name, float price, int rating)
: name_(name), price_(price), rating_(rating) {}
};
A taste of old C++ (C++98)
15. 15
ostream & operator<<(ostream & to, const place & p) {
to << setw(20) << left << p.name_ << "[" << p.rating_ << "]"
<< setw(7) << right << p.price_;
return to;
}
template<class C>
void print(const C & places) {
for(typename C::const_iterator i = places.begin(); i != places.end(); ++i)
cout << *i << endl;
cout << endl;
}
A taste of old C++ (C++98)
16. 16
bool compare_by_rating_price_name(const place & a, const place & b) {
bool result = false;
if(a.rating_ < b.rating_) result = true;
else if(a.rating_ == b.rating_) {
if(a.price_ < b.price_) result = true;
else if(a.price_ == b.price_) result = (a.name_ < b.name_);
}
return result;
}
bool compare_by_name(const place & a, const place & b) {
return a.name_ < b.name_;
}
A taste of old C++ (C++98)
17. 17
vector<place> get_places() {
vector<place> places;
places.push_back(place("Moscow", 1500, 3));
places.push_back(place("St. Petersburg", 1300, 5));
places.push_back(place("Minsk", 500, 4));
places.push_back(place("Tokyo", 3500, 4));
places.push_back(place("Sydney", 5000, 3));
places.push_back(place("Paris", 3000, 5));
places.push_back(place("London", 3500, 4));
return places;
}
A taste of old C++ (C++98)
18. 18
int main() {
vector<place> places = get_places();
sort(places.begin(), places.end(), compare_by_rating_price_name);
print(places);
sort(places.begin(), places.end(), compare_by_name);
print(places);
}
A taste of old C++ (C++98)
19. 19
2003-2011: long-term construction under the name of C++0x.
2011: C++11 released. It's a very different beast!
many, many language improvements;
significant extension of stdlib;
2014: C++14 released. A minor update with some very useful features.
2017: draft of C++17. An important update with lot of new features and
additions to stdlib.
2017: work on C++20 started.
2003-2017: main milestones
21. 21
ostream & operator<<(ostream & to, const place & p) {
fmt::print(to, "{:<20}[{}]{:7}", p.name_, p.rating_, p.price_);
return to;
}
void print(auto & places) {
for(const auto & p : places)
cout << p << endl;
cout << endl;
}
A taste of modern C++ (C++17)
22. 22
bool compare_by_rating_price_name(const place & a, const place & b) {
return tie(a.rating_, a.price_, a.name_) < tie(b.rating_, b.price_, b.name_);
}
bool compare_by_name(const place & a, const place & b) {
return a.name_ < b.name_;
}
A taste of modern C++ (C++17)
23. 23
vector<place> get_places() {
return {
{"Moscow", 1500, 3},
{"St. Petersburg", 1300, 5},
{"Minsk", 500, 4},
{"Tokyo", 3500, 4},
{"Sydney", 5000, 3},
{"Paris", 3000, 5},
{"London", 3500, 4}
};
}
A taste of modern C++ (C++17)
24. 24
int main() {
auto places = get_places();
sort(begin(places), end(places), compare_by_rating_price_name);
print(places);
sort(begin(places), end(places), compare_by_name);
print(places);
}
A taste of modern C++ (C++17)
25. 25
A shot look to the full demo source code…
1985-2017: the comparison
26. 26
#include <iostream.h>
#include <iomanip.h>
#include <string.h>
#include <stdlib.h>
struct place {
char * name_;
long price_;
int rating_;
place() : name_(0) {}
place(const char * name, long price, int rating)
: name_(copy_name(name)), price_(price), rating_(rating)
{}
place(const place & o)
: name_(copy_name(o.name_)), price_(o.price_),
rating_(o.rating_) {}
~place() {
delete[] name_;
}
place & operator=(const place & o) {
char * copy = copy_name(o.name_);
delete[] name_;
name_ = copy;
price_ = o.price_;
rating_ = o.rating_;
return *this;
}
static char * copy_name(const char * src) {
char * r = 0;
if(src) {
r = new char[strlen(src) + 1];
strcpy(r, src);
}
return r;
}
};
ostream & operator<<(ostream & to, const place & p) {
to << setw(20) << left << p.name_ << "[" << p.rating_ <<
"]"
<< setw(7) << right << p.price_;
return to;
}
void print(const place * places, size_t count) {
for(size_t i = 0; i != count; ++i)
cout << places[i] << endl;
cout << endl;
}
int compare_by_rating_price_name(const void * av, const
void * bv) {
const place & a = *(const place *)av;
const place & b = *(const place *)bv;
int result;
if(a.rating_ < b.rating_) result = -1;
else {
if(a.rating_ == b.rating_) {
if(a.price_ < b.price_) result = -1;
else {
if(a.price_ == b.price_) {
result = strcmp(a.name_, b.name_);
}
else result = 1;
}
}
else result = 1;
}
return result;
}
int compare_by_name(const void * av, const void * bv) {
const place & a = *(const place *)av;
const place & b = *(const place *)bv;
return strcmp(a.name_, b.name_);
}
void get_places(place *& places, size_t & count) {
places = new place[7];
places[0] = place("Moscow", 1500, 3);
places[1] = place("St. Petersburg", 1300, 5);
places[2] = place("Minsk", 500, 4);
places[3] = place("Tokyo", 3500, 4);
places[4] = place("Sydney", 5000, 3);
places[5] = place("Paris", 3000, 5);
places[6] = place("London", 3500, 4);
count = 7;
}
int main() {
place * places;
size_t count;
get_places(places, count);
qsort(places, count, sizeof(place),
compare_by_rating_price_name);
print(places, count);
qsort(places, count, sizeof(place), compare_by_name);
print(places, count);
delete[] places;
}
A taste of… Full text of pre-C++98 demo
27. 27
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
struct place {
string name_;
long price_;
int rating_;
place() {}
place(const char * name, float price, int rating)
: name_(name), price_(price), rating_(rating) {}
};
ostream & operator<<(ostream & to, const place & p) {
to << setw(20) << left << p.name_ << "[" << p.rating_ << "]"
<< setw(7) << right << p.price_;
return to;
}
template<class C>
void print(const C & places) {
for(typename C::const_iterator i = places.begin(); i != places.end(); ++i)
cout << *i << endl;
cout << endl;
}
bool compare_by_rating_price_name(const place & a, const place & b) {
bool result = false;
if(a.rating_ < b.rating_) result = true;
else if(a.rating_ == b.rating_) {
if(a.price_ < b.price_) result = true;
else if(a.price_ == b.price_) result = (a.name_ < b.name_);
}
return result;
}
bool compare_by_name(const place & a, const place & b) {
return a.name_ < b.name_;
}
vector<place> get_places() {
vector<place> places;
places.push_back(place("Moscow", 1500, 3));
places.push_back(place("St. Petersburg", 1300, 5));
places.push_back(place("Minsk", 500, 4));
places.push_back(place("Tokyo", 3500, 4));
places.push_back(place("Sydney", 5000, 3));
places.push_back(place("Paris", 3000, 5));
places.push_back(place("London", 3500, 4));
return places;
}
int main() {
vector<place> places = get_places();
sort(places.begin(), places.end(), compare_by_rating_price_name);
print(places);
sort(places.begin(), places.end(), compare_by_name);
print(places);
}
A taste of… Full text of C++98 demo
28. 28
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <tuple>
#include <fmt/format.h>
#include <fmt/ostream.h>
using namespace std;
struct place {
string name_;
long price_;
int rating_;
};
ostream & operator<<(ostream & to, const place & p) {
fmt::print(to, "{:<20}[{}]{:7}", p.name_, p.rating_, p.price_);
return to;
}
void print(auto & places) {
for(const auto & p : places)
cout << p << endl;
cout << endl;
}
bool compare_by_rating_price_name(const place & a, const place & b) {
return tie(a.rating_, a.price_, a.name_) < tie(b.rating_, b.price_, b.name_);
}
bool compare_by_name(const place & a, const place & b) {
return a.name_ < b.name_;
}
vector<place> get_places() {
return {
{"Moscow", 1500, 3},
{"St. Petersburg", 1300, 5},
{"Minsk", 500, 4},
{"Tokyo", 3500, 4},
{"Sydney", 5000, 3},
{"Paris", 3000, 5},
{"London", 3500, 4}
};
}
int main() {
auto places = get_places();
sort(begin(places), end(places), compare_by_rating_price_name);
print(places);
sort(begin(places), end(places), compare_by_name);
print(places);
}
A taste of… Full text of C++17 demo
30. 30
A very weak computers. Fight for efficiency is the fight for a life.
Personal Computer was not a toy anymore. It was a new market.
But PCs were yet more weak: "640K ought to be enough for anybody"
OOP was regarded as a "silver bullet" for a software development crisis.
There was a necessity of a complex tool for solving complex problems.
Because almost every problem was a complex one.
C++ was a such tool.
Where was IT-industry at mid of 1980s?
31. 31
Almost everywhere:
– system software;
– middleware;
– server-side;
– desktop (especially on Windows with OLE/COM/DCOM);
– embedded;
– high-performance computing;
– ...
With obvious exceptions in areas where tools like dBase, FoxBase, Clarion,
VisualBasic were in active use.
Where C++ was used before 2000s?
32. 32
Computers become much more powerful.
– Java is not slow now (or it is believed that Java is not slow);
– Microsoft created .NET and C#. Development for Windows is now .NET-centric;
– many application are developed in Python, Ruby, Erlang and so on.
Internet and WWW are not toys anymore. They are a new market.
– Web-development is a new niche;
– migration from desktop to Web has started...
IT-landscape changed at the end of 90s
33. 33
Started at the beginning of 2000s.
Many developers switched to more safe and powerful languages and
platforms like JVM (Java, Scala), .NET (C#, F#), Python, Ruby, Erlang and so
on...
New projects didn't use C++.
Migration of some old projects to other languages started.
Visual Studio as an example.
New big platforms: Apple iOS (Objective-C) and Google's Android (Java).
Hype around Erlang, OCaml, Haskell and similar languages.
The oblivion of C++
35. 35
There are objective and subjective reasons.
It is hard to speak about subjective reasons seriously:
– too many features, a developer must think (think?!!!);
– it is not Java nor C# nor SmallTalk nor ...
– the OOP is C++ is totally wrong (so speak Alan Key);
– no Garbage Collector.
But there are some objective reasons which make life of a programmer
harder...
C++ became a monster long time ago
36. 36
C++98 is almost 800 pages.
C++11 is about 1400 pages.
C++17 is about 1700 pages.
Must read books for a C++ developer (only some of them):
"The C++ Programming Language" (Bjarne Stroustrup), "C++ Standard Library Tutorial and
Reference" (Nicolai Josuttis), "C++ Templates: The Complete Guide" (David Vandevoorde and
Nicolai M. Josuttis), "C++ Coding Standards" (Herb Sutter and Andrei Alexandrescu), "Effective
Modern C++" (Scott Meyers) and the previous books from the same author: "Effective C++",
"Effective STL", "More Effective C++".
See more here: The Definitive C++ Book Guide and List.
C++ is a complex language
38. 38
There are many ways to corrupt memory of a program:
– dereference of an invalid pointer;
– out of bound writes;
– violation of type rules (an attempt to cast int* to double*);
– use of uninitialized value;
– double free of memory;
– ...
A program with corrupted memory may crash. Or it may not crash (it much
worse).
Even if it crashes there is no beautiful stack trace or something similar.
A program may crash or may not...
39. 39
There are plenty of UB in the language:
– signed overflow;
– access out of bounds;
– uninitialized scalar;
– null pointer dereference;
– access to pointer passed to realloc;
– infinite loop without side-effects;
– oversized shift;
– violation of type rules;
– modification of the same scalar more than once in an expression;
– ...
Undefined behavior
40. 40
#include <cstdlib>
typedef int (*Function)();
static Function Do;
static int EraseAll() {
return system("rm -rf /");
}
void NeverCalled() {
Do = EraseAll;
}
int main() {
return Do();
}
Undefined behavior (`rm -rf /`)
41. 41
#include <cstdlib>
typedef int (*Function)();
static Function Do;
static int EraseAll() {
return system("rm -rf /");
}
void NeverCalled() {
Do = EraseAll;
}
int main() {
return Do();
}
Undefined behavior (`rm -rf /`)
43. 43
sort(begin(places), end(places), [](const auto & a, const auto & b) {
const auto t = [](const auto & p) { return tie(p.rating_, p.price_, p.name_); };
return t(a) < tie(b);
});
Hard to read error messages
44. 44
Hard to read error messages
In file included from t1_cpp14_2.cpp:5:0:
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tuple: In instantiation of 'constexpr bool std::operator<(const std::tuple<_Tps ...>&, const
std::tuple<_Elements ...>&) [with _TElements = {const int&, const long int&, const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&}; _UElements =
{const place&}]':
t1_cpp14_2.cpp:40:16: required from 'main()::<lambda(const auto:1&, const auto:2&)> [with auto:1 = place; auto:2 = place]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/predefined_ops.h:143:18: required from 'constexpr bool
__gnu_cxx::__ops::_Iter_comp_iter<_Compare>::operator()(_Iterator1, _Iterator2) [with _Iterator1 = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Iterator2 =
__gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = main()::<lambda(const auto:1&, const auto:2&)>]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:81:17: required from 'void std::__move_median_to_first(_Iterator, _Iterator, _Iterator,
_Iterator, _Compare) [with _Iterator = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const auto:1&,
const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:1921:34: required from '_RandomAccessIterator
std::__unguarded_partition_pivot(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<place*,
std::vector<place> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const auto:1&, const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:1953:38: required from 'void std::__introsort_loop(_RandomAccessIterator,
_RandomAccessIterator, _Size, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Size = long long int; _Compare =
__gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const auto:1&, const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:1968:25: required from 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator,
_Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const
auto:1&, const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:4868:18: required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter =
__gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = main()::<lambda(const auto:1&, const auto:2&)>]'
t1_cpp14_2.cpp:41:4: required from here
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tuple:1413:7: error: static assertion failed: tuple objects can only be compared if they have equal sizes.
static_assert(sizeof...(_TElements) == sizeof...(_UElements),
^~~~~~~~~~~~~
sort(begin(places), end(places), [](const auto & a, const auto & b) {
const auto t = [](const auto & p) { return tie(p.rating_, p.price_, p.name_); };
return t(a) < tie(b);
});
45. 45
sort(begin(places), end(places), [](const auto & a, const auto & b) {
const auto t = [](const auto & p) { return tie(p.rating_, p.price_, p.name_); };
return t(a) < tie(b);
});
Hard to read error messages
In file included from t1_cpp14_2.cpp:5:0:
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tuple: In instantiation of 'constexpr bool std::operator<(const std::tuple<_Tps ...>&, const
std::tuple<_Elements ...>&) [with _TElements = {const int&, const long int&, const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&}; _UElements =
{const place&}]':
t1_cpp14_2.cpp:40:16: required from 'main()::<lambda(const auto:1&, const auto:2&)> [with auto:1 = place; auto:2 = place]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/predefined_ops.h:143:18: required from 'constexpr bool
__gnu_cxx::__ops::_Iter_comp_iter<_Compare>::operator()(_Iterator1, _Iterator2) [with _Iterator1 = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Iterator2 =
__gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = main()::<lambda(const auto:1&, const auto:2&)>]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:81:17: required from 'void std::__move_median_to_first(_Iterator, _Iterator, _Iterator,
_Iterator, _Compare) [with _Iterator = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const auto:1&,
const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:1921:34: required from '_RandomAccessIterator
std::__unguarded_partition_pivot(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<place*,
std::vector<place> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const auto:1&, const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:1953:38: required from 'void std::__introsort_loop(_RandomAccessIterator,
_RandomAccessIterator, _Size, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Size = long long int; _Compare =
__gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const auto:1&, const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:1968:25: required from 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator,
_Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const
auto:1&, const auto:2&)> >]'
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/stl_algo.h:4868:18: required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter =
__gnu_cxx::__normal_iterator<place*, std::vector<place> >; _Compare = main()::<lambda(const auto:1&, const auto:2&)>]'
t1_cpp14_2.cpp:41:4: required from here
C:/mingw64-posix-7.2.0/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tuple:1413:7: error: static assertion failed: tuple objects can only be compared if they have equal sizes.
static_assert(sizeof...(_TElements) == sizeof...(_UElements),
^~~~~~~~~~~~~
841 lines
46. 46
No standard dependency manager and central dependency repository.
There is some activity last years: buckaroo, build2, cget, conan, conda, cpm, cppan, hunter,
vcpkg, ...
But there is no a clear winner yet.
No standard build tool.
There are lot of tools in use: bazel, build2, buckaroo, cmake, make, meson, scons, waf, ...
But there is no de-jure standard.
It seems that CMake becomes a de-facto standard.
Infrastructure from a 1980s
47. 47
Addition of STL into C++98 made life of developers easier.
Extension of stdlib in C++11 made life yet more easier.
Another extension of stdlib in C++17 will made life yet more easier...
But C++'s stdlib still looks very poor with comparison with other popular
languages like Java, C#, Python, Ruby and so on.
Shine and poverty of C++ stdlib
48. 48
Many developers just don't know how to use C++ safely and efficiently.
Mantra "learn C first and only then C++" is terribly wrong!
C++ as a first language? May be not a good idea.
Plain old C as a first language? It's much worse!
People's factor
50. 50
Procedural Programming
Object-Oriented Programming (incl. multiple inheritance)
one of the most comprehensive between statically typed OO-languages. Only Eiffel has more
advanced support for OOP.
Generic Programming (function and class templates and all that stuff...)
compile-time duck-typing and static polymorphism.
Functional Programming
All these paradigms can be easily combined in a single program.
C++ is a multiparadigm language
51. 51
+ low resources consumption
+ total control
+ an easy access to OS and hardware.
Lot of resources were invested in optimizing C++ compiler and tools.
There are a very few alternatives with comparable expressiveness and
execution speed (if any).
High performance...
52. 52
You can add your own "thing" and this "thing" will behave just a language's
first-class citizen.
An ability to create int_set attracted me 25 years ago...
Powerful and cheap abstraction
53. 53
class int_set {
int * items_;
...
public:
int_set() : items_(new int[initial_capacity]) {...}
~int_set() { delete[] items_; }
...
};
int_set operator+(const int_set & a, const int_set & b) {...}
int_set operator-(const int_set & a, const int_set & b) {...}
int_set operator&(const int_set & a, const int_set & b) {...}
int_set received_items;
int_set checked_items;
...
int_set delayed_items = received_items - checked_items;
Powerful and cheap abstraction (int_set)
54. 54
Class matrix is another classical example. Allows to write a compact and
readable code:
const unsigned N = ...;
matrix a(N,N), b(N,N), c(N,N), d(N,N);
...
matrix x = a*b + c*d;
Powerful and cheap abstraction (matrix)
55. 55
Class matrix is another classical example. Allows to write a compact and
readable code:
const unsigned N = ...;
matrix a(N,N), b(N,N), c(N,N), d(N,N);
...
matrix x = a*b + c*d;
Powerful and cheap abstraction (matrix)
A plain C alternative:
matrix a, b, c, d;
matrix ab, cd, x;
matrix_init(&a, N, N);
matrix_init(&b, N, N);
matrix_init(&c, N, N);
matrix_init(&d, N, N);
...
matrix_init(&ab, N, N);
matrix_init(&cd, N, N);
matrix_init(&x);
matrix_mul(&a, &b, &ab);
matrix_mul(&c, &d, &cd);
matrix_add(&ab, &cd, &x);
matrix_destroy(&ab);
matrix_destroy(&cd);
...
matrix_destroy(&x);
matrix_destroy(&d);
matrix_destroy(&c);
matrix_destroy(&b);
matrix_destroy(&a);
56. 56
Get a resource in the constructor.
allocate memory, acquire mutex, open file, create painting device, ...
Release the resource in the destructor.
destructor is called automatically when object is out of scope or destroyed manually.
We have already seen this in int_set example:
class int_set {
int * items_;
...
public:
int_set() : items_(new int[initial_capacity]) {...}
~int_set() { delete[] items_; }
RAII (Resource Acquisition Is Initialization)
57. 57
RAII is used for different types of resources, not only memory:
void raii_example() {
ifstream file{"input.dat", ios::binary};
if(file.is_open()) {
vector<uint8_t> content = load_data(file);
...
lock_guard<mutex> lock{global_data_lock};
global_data = move(content);
global_data_updated.notify();
}
}
RAII (Resource Acquisition Is Initialization)
58. 58
RAII is used for different types of resources, not only memory:
void raii_example() {
ifstream file{"input.dat", ios::binary};
if(file.is_open()) {
vector<uint8_t> content = load_data(file);
...
lock_guard<mutex> lock{global_data_lock};
global_data = move(content);
global_data_updated.notify();
}
}
RAII (Resource Acquisition Is Initialization)
59. 59
C++ is great for creation of high-level domain specific tools.
High-level domain-specific tools
60. 60
class User {
public:
...
static User fromJSON(const rapidjson::Value& doc) {
if(!doc.IsObject())
throw std::runtime_error("document should be an object");
static const char* members[] = { "id", "name", "phone", "birthday" };
for(size_t i = 0; i < sizeof(members)/sizeof(members[0]); i++)
if(!doc.HasMember(members[i])) throw std::runtime_error("missing fields");
uint64_t id = doc["id"].GetUint64();
std::string name = doc["name"].GetString();
uint64_t phone = doc["phone"].GetUint64();
Date birthday = Date::fromJSON(doc["birthday"]);
User result(id, name, phone, birthday);
return result;
}
};
Domain specific tools (JSON example)
RapidJSON
63. 63
Use only that you know.
Any safe subset of C++ is still C++.
Common sense rulezzz!
64. 64
There are a lot of for different application areas:
– C++ Core Guidelines;
– guidelines from famous companies or projects (Google's, Boost's,
Mozilla's, Bloomberg's, CERT's, ...);
– industry-specific standard and/or guidelines (Joint Strike Fighter Air
Vehicle C++ Coding Standards, MISRA C++, High Integrity C++,...)
Use guidelines
65. 65
Static code analyzers:
– cppcheck;
– clang static analyzer;
– Coverity;
– PVS-Studio.
Sanitizers (GCC, clang):
– address;
– thread;
– leak;
– undefined.
Compiler flags like -Wall, -Weverything and -Werror are your friends!
Use analyzers and sanitizers
66. 66
/// Open a device and get handle for it.
///
/// attention A dynamically allocated object returned. Caller must deallocate it.
device * open_device(
/// Name of device to be created.
const char * dev_name,
/// Creation options.
device_options options);
...
auto dev = open_device("lpt1", defaults);
dev->write(...);
...
delete dev;
Use right abstractions (1)
67. 67
/// Open a device and get handle for it.
unique_ptr<device> open_device(
/// Name of device to be created.
const char * dev_name,
/// Creation options.
device_options options);
...
auto dev = open_device("lpt1", defaults);
dev->write(...);
...
Use right abstractions (2)
68. 68
Many developers abandon type-safe API if it requires a lot of boilerplate
code:
ostream & operator<<(ostream & o, const place & p) {
o << setw(20) << left << p.name_ << "[" << p.rating_ << "]"
<< setw(7) << right << p.price_;
return o;
}
Use right libraries (type safety)
69. 69
And use something more "useful" and/or "powerful":
ostream & operator<<(ostream & o, const place & p) {
char buf[30];
snprintf(buf, sizeof(buf), "%-20s[%d]%7d", p.name_, p.rating_, p.price_);
return (o << buf);
}
Use right libraries (type safety)
70. 70
And use something more "useful" and/or "powerful":
ostream & operator<<(ostream & o, const place & p) {
char buf[30];
snprintf(buf, sizeof(buf), "%-20s[%d]%7d", p.name_, p.rating_, p.price_);
return (o << buf);
}
Use right libraries (type safety)
30 characters required for textual
representation. But addition character is
necessary for terminating 0-symbol.
place::price_ is unsigned long, "%7ld"
must be used instead of "%7d".
place::name_ is std::string, not
char*, place.name_.c_str() must be
used.
71. 71
There are powerful and type-safe libraries. fmtlib as an example:
#include <fmt/format.h>
#include <fmt/ostream.h>
ostream & operator<<(ostream & o, const place & p) {
fmt::print(o, "{:<20}[{}]{:7}", p.name_, p.rating_, p.price_);
return o;
}
Use right libraries (type safety)
72. 72
How many lines of modern C++ are necessary to write the simplest HTTP-
server?
A server that responds "Hello, world" for all requests?
Use right libraries (simplicity)
77. 77
IT-landscape has changed but there are still many areas where high
performance and low resource consumptions matter.
Smartphones and mobile development are here. Battery life matters.
High diversity of devices in use: PC, laptops/netbooks, tablets, smartphones,
smart watches, smart TVs, game consoles, ...
Big server farms.
Free lunch is over. It's not an easy to take a performance gain now.
The return of interest in native code apps.
2011-2017: what's changed?
78. 78
C++ Futures on Instagram: high-performing recommendation service was
rewritten in C++.
number of servers reduced from 720 to 38.
Speedup PHP at Facebook: HipHop (PHP-to-C++ transpiler) and HHVM
(HipHop Virtual Machine).
Some examples. Server-side
79. 79
ScyllaDB: a high performance drop-in replacement for Cassandra.
10x better performance on high-end hardware, 1.5x-3x better on smaller machines.
Quantcast File System: a high performance alternative to HDFS (Hadoop
Distributed File System) written in C++.
50% space reduction, +75% write and +45% read throughput.
Some examples. Middleware
80. 80
Doodle Kindom: cross-plaform games with kernel in C++.
works on iPhone, iPad, Windows, MacOS, NOOK.
Oncam: a videochat system for iOS+Android with kernel in C++.
supports videochat up to 6 participant with at least 15FPS.
Some examples. Mobile
81. 81
High performance computing
– weather forecasting, molecular modeling, physic simulation, big-data, machine learning, ...
Low resource consumption
– mobile application, internet of things, ...
System programming (and around)
– OS kernels, drivers and utilities, middleware, compilers, antiviruses, ...
Real-time and embedded systems
– SCADA, industrial internet of things, avionics, automotive, finance, telecom, defense, ...
Complex desktop applications
– CADs, photoshop, AAA games, browsers, office apps, ...
Cross-platform apps
– app's kernel in C++ + GUI in native technology (Dropbox's jinie), ...
Legacy
Where C++ can be used now?
82. 82
There is no place for quick-
and-dirty solutions!
What is in common?
84. 84
Java and C#:
It is not actual anymore :) Java and C# already ate everything they could.
plain C:
It is actual again. Suddenly?
Go:
Shines in its very narrow niche. Attracts much more Python/Ruby developers than C++ devs.
Rust:
The only real modern alternative to C++ now. But it is a hard question.
Main alternatives
85. 85
Ada:
Very strong competitor for embedded and real-time areas. Almost unknown in East Europe.
D:
It's too late. Lack of popularity and presence of GC.
Swift:
Almost nonexistent outside the Apple's ecosystem.
Some other alternatives
87. 87
There is no commercial force behind it (like Oracle for Java, Microsoft for
C#, JetBrains for Kotlin and so on).
If you need something in C++ you can propose it: https://stdcpp.ru/
C++ is community driven language