A minimal collection of most wanted and widely accepted idioms and coding conventions for C++ development presented with examples and explanations. The lecture targets performance oriented codes so emphasis is on performance-friendly techiques.
Topics covered:
1) Design issues: idioms and best practices
- Resource Aquisition Is Initialization (RAII)
- Ownership semantics and smart pointers
- Header files: dependencies and decoupling
2) Objects Construction/Destruction/Copying
- Designing constructors
- Rule Of Three
- Transactional programming
3) Namespaces
- ADL/Koenig Lookup
4) Static analyzers
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
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.
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
••• Exploit the full potential of the CRTP! •••
In this presentation you will learn:
▸ what is the curiously recurring template pattern
▸ the actual cost (memory and time) of virtual functions
▸ how to implement static polymorphism
▸ how to implement expression templates to avoid loops and copies
Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
If virtual functions in C++ imply design patterns, then C++ lambdas imply what? What does it really mean to have lambdas in C++? Frankly, I don't know but I've a hunch: It's BIG.
Just like virtual functions open doors to the OO paradigm, lambdas open doors to a different paradigm--the functional paradigm. This talk is not a praise of functional programming or some elusive lambda-based library. (Although, I'll mention one briefly that tops my list these days.) Instead, the goal is to have fun while working our way through some mind-bending examples of C++14 lambdas. Beware, your brain will hurt! Bring your laptop and code the examples right along because that may be the fastest way to answer the quiz.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
••• Boost your code's performances using C++11 new features! •••
In this presentation you will learn:
▸ the difference between an Lvalue and Rvalue
▸ how to use std::move, std::forward, noexcept
▸ how to implement move semantics to avoid useless copies
▸ how to implement perfect forwarding for the factory pattern
Improving The Quality of Existing SoftwareSteven Smith
Presented at DevReach 2013.
As developers, most of our time is spent working on existing software. Sure, occasionally we get the chance to fire up a new Solution in Visual Studio, and that can be exciting. But after the first day, we find ourselves once more having to deal with the work we did yesterday. And today, we know more than we did yesterday, so there are things we’d do differently, if we had it to do over.
Over time, software rots. If we’re not diligent, our beautiful code can degrade into a worthless mess. Keeping our code in working condition is no different than changing the oil in our car – it’s preventive maintenance. In this session, Steve will look at some common places to look for signs of degradation in existing applications, and steps to take to improve the code. Examples will use C# and primarily ASP.NET.
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.
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
••• Exploit the full potential of the CRTP! •••
In this presentation you will learn:
▸ what is the curiously recurring template pattern
▸ the actual cost (memory and time) of virtual functions
▸ how to implement static polymorphism
▸ how to implement expression templates to avoid loops and copies
Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
If virtual functions in C++ imply design patterns, then C++ lambdas imply what? What does it really mean to have lambdas in C++? Frankly, I don't know but I've a hunch: It's BIG.
Just like virtual functions open doors to the OO paradigm, lambdas open doors to a different paradigm--the functional paradigm. This talk is not a praise of functional programming or some elusive lambda-based library. (Although, I'll mention one briefly that tops my list these days.) Instead, the goal is to have fun while working our way through some mind-bending examples of C++14 lambdas. Beware, your brain will hurt! Bring your laptop and code the examples right along because that may be the fastest way to answer the quiz.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
••• Boost your code's performances using C++11 new features! •••
In this presentation you will learn:
▸ the difference between an Lvalue and Rvalue
▸ how to use std::move, std::forward, noexcept
▸ how to implement move semantics to avoid useless copies
▸ how to implement perfect forwarding for the factory pattern
Improving The Quality of Existing SoftwareSteven Smith
Presented at DevReach 2013.
As developers, most of our time is spent working on existing software. Sure, occasionally we get the chance to fire up a new Solution in Visual Studio, and that can be exciting. But after the first day, we find ourselves once more having to deal with the work we did yesterday. And today, we know more than we did yesterday, so there are things we’d do differently, if we had it to do over.
Over time, software rots. If we’re not diligent, our beautiful code can degrade into a worthless mess. Keeping our code in working condition is no different than changing the oil in our car – it’s preventive maintenance. In this session, Steve will look at some common places to look for signs of degradation in existing applications, and steps to take to improve the code. Examples will use C# and primarily ASP.NET.
Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11,...Complement Verb
C++11 is being deployed and the shape of C++14 is becoming clear. This talk examines the foundations of C++. What is essential? What sets C++ apart from other languages? How do new and old features support (or distract from) design and programming relying on this essence?
I focus on the abstraction mechanisms (as opposed to the mapping to the machine): Classes and templates. Fundamentally, if you understand vector, you understand C++.
Type safety and resource safety are key design aims for a program. These aims must be met without limiting the range of applications and without imposing significant run-time or space overheads. I address issues of resource management (garbage collection is not an ideal answer and pointers should not be used as resource handles), generic programming (we must make it simpler and safer), compile-time computation (how and when?), and type safety (casts belongs in the lowest-level hardware interface). I will touch upon move semantics, exceptions, concepts, type aliases, and more. My aim is not so much to present novel features and technique, but to explore how C++’s feature set supports a new and more effective design and programming style.
An Introduction to Part of C++ STL for OI. Introduced the common use of STL algorithms and containers, especially those are helpful to OI.
Also with some examples.
The presentation discusses software design. It discusses the characteristics of a good and bad design. Then it talks about how to achieve a good design. Then finally we discuss the SOLID Principles of Object Oriented Design. These are 5 principles compiled by Rober Cecil Martin aka Uncle Bob. The benefit of these principles is to achieve a good OO design which is high in cohesion and low in coupling thus easily adaptable to change
Of the SOLID principles, made famous by Robert C. Martin, we'll discuss the Interface Segregation Principle and the Dependency Inversion Principle. This session will explain them thoroughly and give real life examples instead of the regular customer & order examples. You'll walk away knowing what the benefits are and how to use them properly.
Of the SOLID principles, made famous by Robert C. Martin, we'll discuss the Single Responsibility Principle and the Open/Closed Principle, two of the presenter's favorite principles. But at the same time the least understood and used principles. That's why this session will explain them thoroughly and give real life examples instead of the regular customer & order examples. You'll walk away knowing what the benefits are and how to use them properly.
Abstract Base Class and Polymorphism in C++Liju Thomas
Connect with me through Facebook and twitter for more details:http://www.facebook.com/lijuthomas24, http://www.twitter.com/lijuthomas24
This ppt explains the concept of abstract base class and Polymorphism in C++
Keys to Continuous Delivery Success - Mark Warren, Product Director, Perforc...Perforce
Many well-known SaaS vendors use Continuous Delivery to update production sites at mind-bogglingly short intervals and non-SaaS organizations are increasingly looking to CD to increase customer satisfaction and be more competitive.This session will review case studies by Perforce customers, including NYSE, CCP Games, salesforce.com and others, to identify key success factors and provide recommendations for starting, or accelerating, the adoption of CD in your organization.
Brief overview of the Rust system programming language. Provides a concise introduction of its basic features, with an emphasis on its memory safety features (ownership, moves, borrowing) and programming style with generic functions, structures, and traits.
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
write the To Do\'s to get the exact output:
NOte: A valid Fraction number has a non-negative numerator and a positive denominator.
Default constructor initializes the object to safe empty state (an object with denom equals -1).
The two-argument constructor also validates the parameters and sets the object to the safe empty
state if the parameters are not valid.
Write the definitions and prototypes of following functions in Fraction.cpp and Fraction.h
respectively (They are indicated in the files by //TODO tag):
Define isEmpty function as a member function, which returns true if the object is in safe empty
state (an object is in the safe empty state if denominator (denom) equals -1).
Define display function, which sends a Fraction number to the output stream (with the
“Numerator/denominator” format). This function just prints \"Invalid Fraction Object!\" in the
screen if the object is in the safe empty state. In case that object denominator equals 1, it just
print the numerator.
Define the operator functions for the following operators:
“+=”, “+”, “*”
The overload of the above operators should make the following code possible:
The member operator+ : Adds two Fraction numbers and returns a Fraction number as the result.
This function returns an object with the safe empty state if either of Fraction numbers (operands)
is in safe empty state. It makes following code possible:
A+B ( where A and B are Fraction objects)
The member operator+= : Adds two Fraction numbers and assigns the result to the left operand,
then returns a reference to the left operand. If either of Fraction numbers (operands) is in safe
empty state, it initializes the left operand to the safe empty state, then returns a reference to the
left operand. It makes following code possible:
A+=B ( where A and B are Fraction objects)
The member operator* : Multiplies two Fraction numbers and returns a Fraction number as the
result. This function returns an object with the safe empty state if either of Fraction numbers
(operands) is in safe empty state. It makes following code possible:
A*B ( where A and B are Fraction objects)
fraction.cpp
#include \"Fraction.h\"
using namespace std;
namespace sict{
Fraction::Fraction(){
denom =-1; // safe empty state
}
Fraction::Fraction(int n, int d) // n: numerator, d: denominator
{
if(n >= 0 && d > 0){
num = n;
denom = d;
reduce();
}
else
denom =-1; // set to safe empty state
}
int Fraction::gcd() // returns the greatest common divisor of num and
denom
{
int mn = min(); // min of num and denom
int mx = max(); // mX of num and denom
for (int x=mn ; x > 0 ; x--) // find the greatest common divisor
if( mx % x == 0 && mn % x == 0)
return x;
return 1;
}
void Fraction::reduce() // simplify the Fraction number
{
int tmp = gcd();
num /= tmp;
denom /= tmp;
}
int Fraction::max ()
{
return (num >= denom) ? num : denom;
}
int Fraction::min()
{
return (num >= denom) ? denom : num;
}
// in_lab
// TODO: write the implementation of display function HERE
// TODO: w.
PROGRAM 2 – Fraction Class Problem For this programming as.pdfezonesolutions
PROGRAM 2 – Fraction Class
Problem For this programming assignment, you are to implement the Fraction class design
given below (and discussed in class). You are also to develop an appropriate test driver that
thoroughly tests the class.
Fraction Class Design Implement the following class design. Make sure to use implement the
methods to have the same names as given below, with the same number and types of parameters.
public class Fraction {
private int numer;
private int denom;
// alternate constructor
public Fraction(int numer, int denom)
throws InvalidDenominatorException {
}
// copy constructor
public Fraction(Fraction otherFrac) {
}
// getters
public int getNumer() {
}
public int getDenom() {
}
// standard methods
public String toString() {
}
public boolean equals(Fraction rFrac) {
}
// fraction operators
public Fraction add(Fraction rFrac) {
}
public Fraction sub(Fraction rFrac) {
}
public Fraction mult(Fraction rFrac) {
}
public Fraction div(Fraction rFrac) {
}
public boolean isSimplestForm() {
}
public Fraction reduce() {
}
public boolean properFrac() {
}
public Fraction abs() {
}
public boolean lessThan(Fraction rFrac) {
}
public boolean greaterThan(Fraction rFrac) {
}
public double convertToDecimal() {
}
public Fraction invert() {
}
}
Note that objects of type Fraction are immutable. Also, the alternate constructor throws an
InvalidDenominatorException if passed a denominator value of 0. This exception type is not
predefined in Java, so you must define it as follow as another class in your Java project files:
public class InvalidDenominatorException extends RuntimeException { } // nothing to
implement
This creates an exception of type RuntimeException. RuntimeExceptions do not need to be
caught when thrown. However, your test driver should have the code for catching this exception
where appropriate.
For example, if your test driver excutes the following,
Fraction frac1 = new Fraction(1,2);
then there is no need to catch the possible exception, since it is clear that the denominator is not
0. However, if the value are input by the user, then there is a chance that a denominator vaue of 0
could be entered, and therefore the code for catching the possible exception is needed,
int numer, denom;
Fraction frac1;
Scanner input = new Scanner(System.in);
Boolean valid_input = false;
while (!valid_input) try {
System.out.print(“Enter numerator denominator: “);
numer = input.nextInt();
denom = input.nextInt();
frac1 = new Fraction(numer,denom);
valid_input = true;
}
catch (InvalidDenominatorException e) {
System.out.println(“Denominator of Zero found – Please reenter”);
}
catch (InputMismatchException e) {
System.out.println(“Non-digit character found – Please reenter”);
} etc.
Considerations
Makes sure the equals method returns true for any two fractions that are arithmetically equal.
Make sure that the equals, lessThan and greaterThan methods do not alter the values of the
fractions being compared. You may consider the use of private methods .
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, 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.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
3. Herb Sutter and Andrei Alexandrescu, C++
Coding Standards
Bjarne Stroustrup’s C++ Style and Technique
FAQ [www.stroustrup.com/bs_faq2.html]
stackoverflow.com, C++faq tag
Microsoft Channel 9 [http://channel9.msdn.com/]
Scott Meyers, Effective C++
cppreference.com
Bjarne Stroustrup, The C++ Programming
Language
Federico Ficarelli, Idiomatic C++
3
5. void foo ()
{
char* ch = new char[100];
if (...)
if (...)
return;
else if (...)
if (...)
else
throw "ERROR";
// This may not be invoked...
delete [] ch;
}
void bar ()
{
lock.acquire();
if (...)
if (...)
return;
else
throw "ERROR";
// This may not be invoked...
lock.release();
}
In order to guarantee resources
release, we need to keep track of:
natural return;
return statements;
exceptions thrown.
Issues:
code complexity;
duplicated code (copy and paste);
forces to catch and re-throw
(even if we aren’t able to handle it);
error prone.
Federico Ficarelli, Idiomatic C++
5
6. Exception Safety Rule:
the only code that is guaranteed to be executed after an
exception is thrown are the destructors of objects residing on
the stack.
template <class T>
class AutoDelete
{
public:
AutoDelete (T * p = 0) :
ptr_(p) {}
class ScopedLock
{
public:
ScopedLock (Lock & l) : lock_(l) {
lock_.acquire();
}
~AutoDelete () throw() {
delete ptr_;
}
private:
T *ptr_;
DISALLOW_COPY_AND_ASSIGN(AutoDelete);
};
~ScopedLock () throw () {
lock_.release();
}
private:
Lock& lock_;
DISALLOW_COPY_AND_ASSIGN(ScopedLock);
};
Federico Ficarelli, Idiomatic C++
6
7. RAII:
every time you need to wrap and manage a resource (memory, file,
lock, etc...) in a class, let the constructor acquire and the destructor
release it: the stack semantics will release the resource when it leaves
the scope.
void foo() {
AutoDelete<X> safe_del(new X());
if (...)
if (...)
return;
// No need to call delete here.
// Destructor will delete memory
}
void bar() {
ScopedLock safe_lock(l);
if (...)
if (...)
throw "ERROR";
// No need to call release here.
// Destructor will release the lock
}
Federico Ficarelli, Idiomatic C++
7
8. // Da Stroustrup’s C++ FAQ:
class File_handle {
FILE* p;
public:
File_handle(const char* n, const char* a) {
p = fopen(n,a);
if (p==0) throw errno;
}
File_handle(FILE* pp) {
p = pp;
if (p==0) throw errno;
}
~File_handle() { fclose(p); }
operator FILE*() { return p; }
// ...
};
void f(const char* fn) {
File_handle f(fn,"rw");
// use file through f,
// don't care about release
// ...
}
Federico Ficarelli, Idiomatic C++
8
9. Constructor:
it must acquire the managed resource and, in case of failure,
raise a proper exception. The acquisition process must be RAII
itself (without relying on the destructor).
Destructor:
it starts with a valid and constructed object (guaranteed by
constructor) and must release the resource. It cannot fail.
Single Responsibility Principle:
every class should have a single, clear responsibility and that
responsibility should be entirely encapsulated by the class.
Federico Ficarelli, Idiomatic C++
9
10.
Automatic lifetime, tightly bound to stack
semantics;
each resource type needs a proper resource
holder;
strict ownership, resources cannot be (easily
and cleanly) passed around.
Federico Ficarelli, Idiomatic C++
10
11. Ownership Semantics:
an object owns a resource when it has the responsibility to release
that resource.
How can we explicitly express ownership in C++?
// Header file
// ...
// AMAZING documentation about
// the following function.
Resource* get_resource();
// ...
struct Resource {
void foo() { /* ... */}
};
Resource* get_resource() {
return new Resource;
// Ownership implicitly transferred to the caller
}
int main (void) {
get_resource()->foo(); // ?
}
Federico Ficarelli, Idiomatic C++
11
12. Strict ownership, transfer allowed
Strict ownership, transfer not allowed
std::auto_ptr<T>
std::unique_ptr<T>
(C++03)
(C++11)
boost::scoped_ptr<T>
(no std)
const std::auto_ptr<T> (C++03)
std::tr1::scoped_ptr
(C++03)
boost::shared_ptr<T>
(no std)
std::tr1::shared_ptr<T> (TR1)
std::shared_ptr<T>
(C++11)
Shared (multiple) ownership
boost::weak_ptr<T>
std::tr1::weak_ptr<T>
std::weak_ptr<T>
(no std)
(TR1)
(C++11)
Federico Ficarelli, Idiomatic C++
12
13. Strict Ownership, Transfer Allowed:
the auto_ptr has semantics of strict ownership, meaning that there is only one
auto_ptr instance responsible for the object's lifetime. If an auto_ptr is copied, the
source loses the reference.
#include <memory>
int main() {
T* pt1 = new T;
#include <memory>
int main() {
std::auto_ptr<T> pt( new T );
}
// <-- ~T()
// pass ownership to an auto_ptr
std::auto_ptr<T> pt2( pt1 );
*pt2 = 12;
// same as "*pt1 = 12;
pt2->SomeFunc(); // same as "pt1->SomeFunc();
// use get() to see the pointer value
assert( pt1 == pt2.get() );
// use release() to take back ownership
T* pt3 = pt2.release();
// no owner, no auto-delete!
delete pt3;
}
Same semantics as raw ptr;
when the owner goes out of
scope, raw ptr is destroyed
(operator delete);
we can release ownership
and take back the raw ptr.
Federico Ficarelli, Idiomatic C++
13
14. int main() {
auto_ptr<T> pt( new T(1) );
pt.reset( new T(2) );// ~T(1), owns T(2)
} // ~T(2)
int main() {
auto_ptr<T> pt1( new T
auto_ptr<T> pt2;
//
pt1->DoSomething(); //
pt2 = pt1;
//
pt2->DoSomething(); //
pt1->DoSomething(); //
} // ~T()
); // pt1 owns
pt2 non-owning
ok
pt1 -> pt2
ok
!!!
Ownership can be explicitly dropped and set
on the fly (reset);
a non-owning auto_ptr has the same
semantics as NULL pointer: never
dereference it (check with operator bool).
Federico Ficarelli, Idiomatic C++
14
15.
No custom deleter, can manage objects
allocated with operator new only;
copying and assigning changes the owner of
a resource, modifying not only the lhs but
also the rhs, which breaks assignment
semantics;
cannot be used in stl
containers.
std::vector< std::auto_ptr<T> > v;
/* ... */
std::sort( v.begin(), v.end() ); // ?
Federico Ficarelli, Idiomatic C++
15
16. Strict Ownership, Transfer Not Allowed:
the scoped_ptr has semantics of strict ownership, meaning that there is only one
scoped_ptr instance responsible for the object's lifetime. The owning scoped_ptr
cannot be copied, ownership cannot be transferred.
Used to show explicit ownership;
supports custom deleter;
useful for automatic deletion of local objects
or class members (PIMPL, RAII, etc...)
can be “simulated” using the
const auto_ptr Idiom.
const auto_ptr<T> pt1( new T );
auto_ptr<T> pt2( pt1 ); // illegal
auto_ptr<T> pt3;
pt3 = pt1;
// illegal
pt1.release();
// illegal
pt1.reset( new T );
// illegal
Federico Ficarelli, Idiomatic C++
16
17. Shared Ownership:
the shared_ptr has semantics of multiple ownership, meaning that multiple owning
instances are allowed at a time. The instance is reference counted*: it will be destroyed
only when the last owner is released.
Useful when object’s lifetime is complex and
not tied to a particular scope/object;
supports custom deleter;
can be safely used inside stl containers.
Federico Ficarelli, Idiomatic C++
17
19. template<class T> class decorator {
private:
T * p_;
public:
explicit pointer(T * p): p_(p) {}
shared_ptr<T> operator->() const {
p_->prefix();
return std::tr1::shared_ptr<T>(p_, std::mem_fn(&T::suffix));
}
};
class X {
private:
void prefix();
void suffix();
friend class decorator<X>;
public:
void f();
void g();
};
int main() {
X x;
decorator<X> px(&x);
px->f();
px->g();
}
Federico Ficarelli, Idiomatic C++
19
20.
Expresses «weak» (latent) ownership;
must be casted to shared_ptr before actual
use (no operators);
essential to break reference cycles.
typedef std::tr1::shared_ptr<T> sh_ptr;
typedef std::tr1::weak_ptr<T> wk_ptr;
typedef std::tr1::shared_ptr<T> sh_ptr;
struct T {
sh_ptr other;
};
void test() {
sh_ptr p1
sh_ptr p2
p1->other
p2->other
} // ?
(new T());
(new T());
= p2; // p1 -> p2
= p1; // p2 -> p1
struct T {
wk_ptr other;
};
void test() {
sh_ptr p1 (new T());
sh_ptr p2 (new T());
if( sh_ptr p = p1->other.lock() ) {
p(p2); // p1 -> p2
}
if( sh_ptr p = p2->other.lock() ) {
p(p1); // p2 -> p1
}
} // ?
Federico Ficarelli, Idiomatic C++
20
21. Resource Return Idiom:
never return raw pointers from within functions; prefer conveying resource ownership
explicitly in the return type.
Makes factory
functions ownership
explicit;
use any type of smart
ptr (depending on your
needs);
improves robustness
dramatically.
// Header file
// ...
// AMAZING documentation about
// the following function.
std::auto_ptr<Resource> get_resource();
// ...
struct Resource {
void foo() { /* ... */}
/* ... */
};
std::auto_ptr<Resource> get_resource() {
return std::auto_ptr<Resource>( new Resource );
// Ownership EXPLICITLY transferred
// to the caller
}
int main (void) {
get_resource()->foo(); // ~Resource()
}
Federico Ficarelli, Idiomatic C++
21
22. Header files should be written to:
be self-sufficient;
be portable;
minimize dependencies;
avoid pollution of client’s names search
space.
Federico Ficarelli, Idiomatic C++
22
23. #ifndef _DATE_H_
#define _DATE_H_
void set_date(int month, int day, int year) {
month_ = month;
day_ = day;
year_ = year;
}
#include <iostream>
#include <math.h>
#include <muslimdate.h>
using namespace std;
inline void Convert(MuslimDate* other) {
// Some heavy work...
// from math.h:
double res = exp(somevalue);
// ...
*other = MuslimDate(/*...*/)
}
namespace calendar {
class Date
{
private:
int month_, day_, year_;
inline int get_month() { return month_; }
inline get_day() { return day_; }
inline get_year() { return year_; }
friend ostream & operator<<
(ostream &os, const Date& d);
};
public:
Date() {
set_date( 1, 1, 1970 );
}
Date(int month, int day, int year) {
set_date(month, day, year);
}
// ...
ostream & operator<<(ostream &os, const Date& date)
{
return os << day_
<< "/"
<< month_ << "/" << year_;
}
} // namespace calendar
#endif // _DATE_H_
Federico Ficarelli, Idiomatic C++
23
24. // date.h
#ifndef IDIOMATICPP_DATE_H_16032013 // <-#define IDIOMATICPP_DATE_H_16032013
#include <iosfwd> // <--
// ...
// Inline Guard Idiom
#if defined(IDIOMATICCPP_USE_INLINE)
#define INLINE inline
#include <date-inl.h>
#endif
namespace calendar {
} // namespace calendar
class MuslimDate; // <-- Forward
#endif // IDIOMATICPP_DATE_H_16032013
class Date
{
private:
int month_, day_, year_;
friend std::ostream & operator<<
(std::ostream &os, const Date& d);
public:
Date();
Date(int month, int day, int year);
void set_date(int month, int day, int year);
void Convert(MuslimDate* other);
int get_month();
int get_day();
int get_year();
};
Guards: avoid clashes and
reserved identifiers;
prefer forward declarations;
remove unused inclusions;
remove using statements;
be sure that the pure header
is made of declarations only.
Federico Ficarelli, Idiomatic C++
24
25.
Collect all inline
definitions in a separate
header;
beware of C std
headers;
no using statements
(qualify all identifiers);
be sure that the inline
header is made of inline
definitions only.
// date-inl.h
#ifndef IDIOMATICPP_DATE_INL_H_16032013 // <-#define IDIOMATICPP_DATE_INL_H_16032013
#include <muslimdate.h>
#include <cmath> // <-#include <date.h>
INLINE void Date::Convert(MuslimDate* other) {
// Some heavy work...
double res = std::exp(somevalue); // <-// ...
*other = MuslimDate(/*...*/)
}
INLINE int Date::get_month() { return month_; }
INLINE int Date::get_day() { return day_; }
INLINE int Date::get_year() { return year_; }
#endif // IDIOMATICPP_DATE_INL_H_16032013
Federico Ficarelli, Idiomatic C++
25
26. #include <date.h>
#if !defined(IDIOMATICCPP_USE_INLINE) // <-#define INLINE
#include <date-inl.h>
#endif
#include <iostream>
// ...from date.h:
// ...
// Inline Guard Idiom
#if defined(IDIOMATICCPP_USE_INLINE)
#define INLINE inline
#include <date-inl.h>
#endif
// ...
using namespace std; // <-using namespace calendar;
Date::Date() { set_date( 1, 1, 1970 ); }
Date::Date(int month, int day, int year) {
set_date(month, day, year);
}
void Date::set_date(int month, int day, int year) {
month_ = month;
day_ = day;
year_ = year;
}
ostream & operator<<(ostream &os, const Date& date)
{
return os << day_ << "/"
<< month_ << "/" << year_;
}
Put the Idiom’s flip
side in a single
implementation file;
inlining can be
controlled by a proper
macro definition.
Federico Ficarelli, Idiomatic C++
26
27.
The vast majority of header-related idioms
care about decoupling;
the main goal is to reduce dependencies and
build time;
accepted downsides could impact
performance.
Federico Ficarelli, Idiomatic C++
27
28.
Classical OO approach to decoupling;
invokes implementation of an abstraction/class
using runtime polymorphism;
Dependency Inversion Principle:
implementation classes should not depend on each other. Instead, they should
depend on common abstraction represented using an interface class.
Federico Ficarelli, Idiomatic C++
28
29. // Abstract base class -> Interface
class Exporter {
public:
virtual std::string
toString(Document* doc) = 0;
};
// Concrete interface implementors (Liskov)
class CSVExporter : public Exporter {
public:
std::string toString(Document* doc)
{ /* ... */ }
};
class XMLExporter : public Exporter {
public:
std::string toString(Document* doc)
{ /* ... */ }
};
// Client (Open Close Principle)
class ExportController {
private:
Exporter* m_exporter; // <-public:
void setExporter(Exporter* exporter);
void runExport();
};
void ExportController::runExport() {
Document* currentDocument =
GetCurrentDocument(); // <-- Factory
// (no ctors)
String exportedString =
m_exporter->toString(currentDocument);
String exportFilePath = GetSaveFilePath();
WriteStringToFile(exporterString, exportFilePath);
}
DIP: ExportController (higher level interface) has no
knowledge of any Exporter subclass (lower level interface);
both depend on abstract Exporter interface (the common
abstraction).
Federico Ficarelli, Idiomatic C++
29
30.
The language makes private members
inaccessible but not invisible;
idiom meant to completely decouple
interface (and clients) from implementation;
implements a true compilation firewall;
consider carefully the advantages (build
time, insulation) and downsides (extra
indirection level).
Federico Ficarelli, Idiomatic C++
30
32. When implementing functionalities, the common belief
is that OO prefers members.
Function Placement:
when implementing new functionalities, prefer non-member non-friend
functions.
Improves encapsulation by minimizing
dependencies: the function cannot depend nonpublic members (“Don’t give away your
internals”);
breaks apart monolithic classes to liberate
separable functionalities, reducing coupling.
Federico Ficarelli, Idiomatic C++
32
33. class NetworkBuffer {
public:
bool empty() {
return
this->device->get_packets_count() == 0;
}
/* ... */
};
class List {
public:
bool empty() {
return
this->length == 0;
}
/* ... */
};
class NetworkBuffer {
public:
size_t size() {
return
this->device->get_packets_count();
}
/* ... */
};
class List {
public:
size_t size() {
return this->length;
}
/* ... */
};
template<class T>
bool empty( const T& s )
{
return s.size() == 0;
}
Federico Ficarelli, Idiomatic C++
33
34. if (f needs to be virtual)
make f a member function of C;
else if (f is operator>> or operator<<)
{
make f a non-member function;
if (f needs access to non-public members of C)
make f a friend of C;
}
else if (f needs type conversions on its left-most
argument)
{
make f a non-member function;
if (f needs access to non-public members of C)
make f a friend of C;
}
else if (f can be implemented via C's public
interface)
make f a non-member function;
else
make f a member function of C;
Functions: the Meyer’s Algorithm [Effective C++]
Federico Ficarelli, Idiomatic C++
34
35. 1.
2.
3.
4.
5.
6.
Ensure resources are owned by objects. Use
explicit RAII and smart pointers to expose
ownership and enforce exception safety.
Give one entity one cohesive responsibility.
Keep your header files clean, don’t harm
clients (nor yourself).
PIMPL and DIP judiciously.
Don’t optimize prematurely:
correctness, simplicity and clarity come first.
Don’t pessimize prematurely.
Federico Ficarelli, Idiomatic C++
35
37. Design and implementation of the Big Four:
default construction,
copy construction;
copy assignment,
destruction.
Pay attention:
compiler can generate them for you;
the language treats classes with value
semantics by deafult.
Federico Ficarelli, Idiomatic C++
37
38. Failing Constructors:
“You should throw an exception from a constructor whenever you cannot
properly initialize (construct) an object. There is no really satisfactory alternative
to exiting a constructor by a throw”. [Stroustrup’s C++ FAQ]
Throwing from within a constructor is the
most safe and widespread technique;
the «init method» technique is unsafe and
breaks RAII and all the idioms discussed in
this chapter.
Federico Ficarelli, Idiomatic C++
38
39. Warning: the constructor itself must be
exception-safe (without relying on destructor).
class T {
public:
T(std::size_t len = 0) :
array( new int[len] ),
buffer( new char[len]) {} // <-- ?
// Destructor (omitted)
private:
int* array;
char* buffer;
};
class T {
public:
T(std::size_t len = 0) :
array( new int[len] ),
buffer( new char[len]) {} // <-- ?
// Destructor (omitted)
private:
std::shared_array<int> array;
std::shared_array<char> buffer;
};
Federico Ficarelli, Idiomatic C++
39
40. Rule Of Three:
if you need to explicitly declare either the destructor, copy constructor or copy
assignment operator yourself, you probably need to explicitly declare all three
of them.
class dumb_string {
public:
dumb_string(std::size_t size = 0) : // conversion/default
mSize(size),
mArray(mSize ? new char[mSize]() : 0) {}
dumb_string(const dumb_string& other) : // copy
mSize(other.mSize),
mArray(mSize ? new char[mSize]() : 0) {
std::copy(other.mArray, other.mArray + mSize, mArray);
}
virtual ~dumb_string() { // destructor
delete [] mArray;
}
private:
std::size_t mSize;
char* mArray;
};
int main() {
dumb_string a(10);
dumb_string b(a);
dumb_string c;
c = a; // ?
}
Federico Ficarelli, Idiomatic C++
40
41. Disable Copying:
whenever it makes sense, explicitly disable copy by construction and by
assignment. This prevents the language from treating types with
unwanted/erratic value semantics.
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
TypeName(const TypeName&);
void operator=(const TypeName&)
// ...
private:
DISALLOW_COPY_AND_ASSIGN(T);
};
template <class T>
class NonCopyable
{
protected:
NonCopyable () {}
~NonCopyable () {} // Protected non-virtual
private:
NonCopyable (const NonCopyable &);
NonCopyable & operator = (const NonCopyable &);
};
class CantCopy : private NonCopyable <CantCopy> {};
CRTP Mixin: enables Empty Base Optimization
Federico Ficarelli, Idiomatic C++
41
42.
We need to implement the copy-assignment
operator in order to have a correct value
semantics;
operator= is much more hard to implement
in a robust way than the copy constructor:
must handle an already constructed object;
in case of failure, it must leave the object in the
previous consistent state (rollback).
The copy-assignment operator must be transactional.
Federico Ficarelli, Idiomatic C++
42
43. dumb_string& operator=(const dumb_string& other)
{
if (this != &other) // <-{
// Tear down object’s state…
delete [] mArray; // <-mArray = 0; // avoid double-deletion in case of RAII
// ...and setup the new one...
mSize = other.mSize; // <-mArray = mSize ? new int[mSize] : 0;
std::copy(other.mArray, other.mArray + mSize, mArray); // <-}
return *this;
}
Issues:
self assignment test: a symptom of non-robust
implementation; usually very rare (performance
waste);
non exception-safe.
Federico Ficarelli, Idiomatic C++
43
44. dumb_string& operator=(const dumb_string& other)
{
if (this != &pOther) // <-{
// setup the new data ready before we teardown the old
std::size_t newSize = other.mSize;
int* newArray = newSize ? new int[newSize]() : 0; // <-std::copy(other.mArray, other.mArray + newSize, newArray);
// replace the old data (all are nothrow)
delete [] mArray;
mSize = newSize;
mArray = newArray;
}
return *this;
}
Issues:
code duplication.
Federico Ficarelli, Idiomatic C++
44
45. friend void swap(dumb_string& first, dumb_string& second) throw()
{
std::swap(first.mSize, second.mSize); // throw()
std::swap(first.mArray, second.mArray); // throw()
}
dumb_string& operator=(const dumb_string& other)
{
dumb_array temp(other);
swap(*this, temp); // <-return *this;
}
dumb_string& operator=(dumb_string other) // <-{
swap(*this, other); // <-return *this;
}
Pass by Value: enables Copy Elision Optimization
Rule-of-Three-and-a-half:
whenever it makes sense, provide a no-fail swap.
Enables strong exception-guarantee (especially the RVO
version);
enables type to be used with a large number of idioms.
Federico Ficarelli, Idiomatic C++
45
46. Foundations Never Fail:
everything that destructor, deallocation (e.g.: operator delete)
and swap functions attempt shall succeed: never allow an error to be
reported from within them. They are the foundation of transactional
programming: without their resilience, no-fail rollback is impossible to
implement.
Federico Ficarelli, Idiomatic C++
46
47. When writing a class, consider:
Rule-of-three(and-a-half) to obtain correct
and robust value semantics for complex
types;
«None-of-three» for POD/aggregates (let the
compiler generate them for you);
explicitly disable copy-construction and copy
assignment.
Federico Ficarelli, Idiomatic C++
47
49. Interface Principle:
for a class T, all functions (including non-member) that both "mention" T
and are "supplied with" T in the same namespace are logically part of
T, because they form part of T's interface.
The language is explicitly designed to enforce
the Interface Principle, ADL/Koenig Lookup
was added for this reason.
Federico Ficarelli, Idiomatic C++
49
50.
Only occurs if the normal lookup of an unqualified
name fails to find a matching class member
function.
“The set of declarations [...] considered for resolution of the
function name is the union of the declarations found by normal
lookup with the declarations found by looking in the set of
namespaces associated with the types of the function
arguments”. [C++03, 3.4.2]
// using namespace std;
std::cout << "hello" << std::endl;
Federico Ficarelli, Idiomatic C++
50
51. namespace type {
class T {
public:
void f();
};
}
namespace ops {
T operator+( const T&, const T& );
}
int main() {
// using ops::operator+;
type::T a, b;
a.f();
type::T c = ops::operator+(a, b);
}
namespace ns {
class T {
public:
void f();
};
T operator+( const T&, const T& );
}
int main() {
ns::T a, b;
a.f();
ns::T c = a + b;
}
Interface Principle, corollary:
keep a type and its non-member function interfaces in the same namespace.
Federico Ficarelli, Idiomatic C++
51
52. #include <vector>
namespace N {
struct X {};
template <typename T> int* operator+( T, unsigned )
{ /* do something */ }
}
int main() {
std::vector<N::X> v(5);
v[0]; // <-- v.begin() + 0
}
Depending on std implementation, ADL may
choose:
std::operator+
N::operator+ (pulled in the name search by
vector<N::X>)
Federico Ficarelli, Idiomatic C++
52
53. «Dual» Interface Principle:
avoid putting non-member functions that are not part of the interface of
a type T into the same namespace as T, and especially never put
templated functions or operators into the same namespace as a userdefined type.
Help prevent name-lookup accidents: protect
types from unwanted ADL.
Federico Ficarelli, Idiomatic C++
53
54. // f1.h
namespace A {
int f(double);
}
// g.h
namespace B {
using A::f;
void g();
}
// f2.h
namespace A {
int f(int);
}
Beware: B::g resolution (and
semantics) depends on the
headers inclusion order.
Namespace Using Principle:
// g.cpp
B::g() {
f(1); // <-- ?
}
avoid putting using namespace directives before any inclusion
directive. Since the inclusion ordering is out of implementor’s control and
depends on client’s implementation, never put using namespace
directives inside header files.
Federico Ficarelli, Idiomatic C++
54