Hexagonal Architecture: The Standard for Qt Embedded ApplicationsBurkhard Stubert
Â
I argue that the hexagonal architecture (aka. ports and adapters pattern) should be the standard architecture for Qt embedded HMIs. I first explain the hexagonal architecture and then show a walking skeleton for a harvester terminal.
C# (pronounced âsee sharpâ or âC Sharpâ) is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002
Hexagonal Architecture: The Standard for Qt Embedded ApplicationsBurkhard Stubert
Â
I argue that the hexagonal architecture (aka. ports and adapters pattern) should be the standard architecture for Qt embedded HMIs. I first explain the hexagonal architecture and then show a walking skeleton for a harvester terminal.
C# (pronounced âsee sharpâ or âC Sharpâ) is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002
OpenGL is a powerful, low-level graphics toolkit with a steep learning curve that allows access to accelerated GPU hardware. Using OpenGL, developers achieve high fidelity, animated graphics ubiquitous in games, screen productions and scientific software.
Join us for a one-hour webinar and we will give a comprehensive overview of the many aspects of OpenGL development where Qt provides advanced interfaces that let the developer focus on the tasks instead of dealing with repetitive and error-prone, platform dependent issues.
Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven for declaring the project configuration.
Ever tried doing Test First Test Driven Development? Ever failed? TDD is not easy to get right. Here's some practical advice on doing BDD and TDD correctly. This presentation attempts to explain to you why, what, and how you should test, tell you about the FIRST principles of tests, the connections of unit testing and the SOLID principles, writing testable code, test doubles, the AAA of unit testing, and some practical ideas about structuring tests.
Convert Your Legacy OpenGL Code to Modern OpenGL with QtICS
Â
See the full Video here: http://bit.ly/modern-open-gl-qt
Back by popular demand, we invite you to another informative webinar on OpenGL, a powerful, low-level graphics toolkit allowing access to accelerated GPU and hardware. Learn the many aspects of OpenGL development where Qt provides advanced interfaces to let developers focus on tasks instead of dealing with repetitive and error-prone, platform dependent issues.
This revised version the OpenGL webinar from last summer, will present information on the differences and the upgrade possibilities available for Qt-OpenGL applications converting from Qt 4x to Qt 5. In addition, we will touch upon best practices when converting legacy, fixed pipeline applications to modern OpenGL using Qt5.
This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.
The Nullable type allows you to assign a null value to a variable. Nullable types can only work with Value Type not with Reference Type because it already contains a null value. The Nullable type is an instance of System.Nullable<T> struct.
Unified Modeling Language (UML) is a modeling language, used for design. Designed based on OMG Standard, Object this helps to express and design documents, software. This is particularly useful for OO design. Here is a brief tutorial that talks about UML usage.
OpenGL is a powerful, low-level graphics toolkit with a steep learning curve that allows access to accelerated GPU hardware. Using OpenGL, developers achieve high fidelity, animated graphics ubiquitous in games, screen productions and scientific software.
Join us for a one-hour webinar and we will give a comprehensive overview of the many aspects of OpenGL development where Qt provides advanced interfaces that let the developer focus on the tasks instead of dealing with repetitive and error-prone, platform dependent issues.
Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven for declaring the project configuration.
Ever tried doing Test First Test Driven Development? Ever failed? TDD is not easy to get right. Here's some practical advice on doing BDD and TDD correctly. This presentation attempts to explain to you why, what, and how you should test, tell you about the FIRST principles of tests, the connections of unit testing and the SOLID principles, writing testable code, test doubles, the AAA of unit testing, and some practical ideas about structuring tests.
Convert Your Legacy OpenGL Code to Modern OpenGL with QtICS
Â
See the full Video here: http://bit.ly/modern-open-gl-qt
Back by popular demand, we invite you to another informative webinar on OpenGL, a powerful, low-level graphics toolkit allowing access to accelerated GPU and hardware. Learn the many aspects of OpenGL development where Qt provides advanced interfaces to let developers focus on tasks instead of dealing with repetitive and error-prone, platform dependent issues.
This revised version the OpenGL webinar from last summer, will present information on the differences and the upgrade possibilities available for Qt-OpenGL applications converting from Qt 4x to Qt 5. In addition, we will touch upon best practices when converting legacy, fixed pipeline applications to modern OpenGL using Qt5.
This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.
The Nullable type allows you to assign a null value to a variable. Nullable types can only work with Value Type not with Reference Type because it already contains a null value. The Nullable type is an instance of System.Nullable<T> struct.
Unified Modeling Language (UML) is a modeling language, used for design. Designed based on OMG Standard, Object this helps to express and design documents, software. This is particularly useful for OO design. Here is a brief tutorial that talks about UML usage.
In this presentation, you will find everything need to get started with AngularJS.
For more details, have a look at my blog (http://stephanebegaudeau.tumblr.com) or follow me on twitter (@sbegaudeau)
There are lots of libraries and frameworks you can use when building browser based JavaScript applications. Probably the most popular library is jQuery. But while jQuery makes it easy to write cross browser user interface code that manipulates the DOM itâs UI focus makes it less then perfect for large business applications. One of the JavaScript based MVC frameworks that has been gaining a lot of popularity for creating business applications is AngularJS. Wen using AngularJS you get the benefit of a powerful data-binding framework that guides you towards a proper application model with a proper separation between the UI layer and the business layer. It also contains a powerful dependency injection framework making code much more testable than before.
In this session Maurice de Beijer will show you how to get started with AngularJS and how productive you can be when creating line of business applications.
Presentation from Denver Open Source Users Group in February 2015. http://www.meetup.com/DOSUG1/events/219099019/
AngularJS is one of today's hottest JavaScript MVC Frameworks. In this session, we'll explore many concepts it brings to the world of client-side development: dependency injection, directives, filters, routing and two-way data binding. We'll also look at its recommended testing tools and build systems. Finally, you'll learn about my experience developing several real-world applications using AngularJS, HTML5 and Bootstrap.
10 Of The Best Books About TCP/IP And Networking
1.Internet Core Protocols: The Definitive Guide: Help for Network Administrators
2.Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs
3.TCP/IP Explained
4.High-Speed Networks TCP/IP and ATM Design Principles
5.TCP/IP: Architecture, Protocols, and Implementation with IPv6 and IP
6.SNMP, SNMPv2, SNMPv3, and RMON 1 and 2
7.SNMP: A Guide to Network Management
8.TCP/IP Network Administration
9.Teach Yourself Tcp/Ip in 14 Days
10.UNIX Network Programming
The sole purpose of sharing these slides are to educate the beginners of IT and Computer Science/Engineering. Credits should go to the referred material and also CICRA campus, Colombo 4, Sri Lanka where I taught these in 2017.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/2J5O3XV.
Howard Chu gives tips and techniques for writing highly efficient and scalable software drawn from decades of experience. The guiding principle is a simple one, and can be applied nearly everywhere. The talk is focused on programming in C. Filmed at qconlondon.com.
Howard Chu founded Symas Corp. with 5 other partners and serves as its CTO. His work has spanned a wide range of computing topics, including most of the GNU utilities, networking protocols and tools, kernel and filesystem drivers, and focused on maximizing the useful work from a system. His current focus is database oriented, covering LDAP, LMDB, and other non-relational database technologies.
The presentation includes brief insight of mostly all important OOPs concepts including Exception Handling, File Handling, Dynamic Memory Allocation, Storage Classes, Namespaces, and Generic Programming.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
Â
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
Â
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties â USA
Expansion of bot farms â how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks â Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
Â
As AI technology is pushing into IT I was wondering myself, as an âinfrastructure container kubernetes guyâ, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefitâs both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
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.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
Â
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. Whatâs changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
Â
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
⢠The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
⢠Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
⢠Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
⢠Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
Â
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more âmechanicalâ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Â
Are you looking to streamline your workflows and boost your projectsâ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, youâre in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part âEssentials of Automationâ series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Hereâs what youâll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
Weâll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Donât miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Â
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overviewâ
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Â
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
Â
C++ 11 Style : A Touch of Class
1. C++11 Style â A Touch of Class
Bjarne Stroustrup
Texas A&M University
www.research.att.com/~bs
2. Abstract
We know how to write bad code: Litter our programs with casts, macros, pointers, naked
new and deletes, and complicated control structures. Alternatively (or in addition), obscure
every design decision in a mess of deeply nested abstractions using the latest object-
oriented programming and generic programming tricks. For good measure, complicate our
algorithms with interesting special cases. Such code is incomprehensible, unmaintainable,
usually inefficient, and not uncommon.
But how do we write good code? What principles, techniques, and idioms can we exploit to
make it easier to produce quality code? I will make an argument for type-rich interfaces,
compact data structures, integrated resource management and error handling, and highly-
structured algorithmic code. I will illustrate my ideas and motivate my guidelines with a few
idiomatic code examples.
I will use C++11 freely. Examples include auto, general constant expressions, uniform
initialization, type aliases, type safe threading, and user-defined literals. C++ features are
only just starting to appear in production compilers, so some of my suggestions have the
nature of conjecture. However, developing a âmodern styleâ is essential if we donât want to
maintain newly-written 1970s and 1980s style code in 2020.
This presentation reflects my thoughts on what âModern C++â should mean in the 2010s: a
language for programming based on light-weight abstraction with a direct and efficient
mapping to hardware, suitable for infrastructure code.
Stroustrup - C++11 Style -
Feb'12
2
3. What is C++?
A multi-paradigm
programming language
Itâs C!
A hybrid language
An object-oriented programming language
Template
meta-programming!
A random collection of features
Embedded systems
programming language
Low level!
Buffer
overflows
Too big!
Generic programming
Stroustrup - C++11 Style -
Feb'12
3
4. C++
Key strengths:
⢠software infrastructure
⢠resource-constrained applications
A light-weight abstraction programming language
Stroustrup - C++11 Style -
Feb'12
4
5. No one size fits all
⢠Different projects have different constraints
â Hardware resources
â Reliability constraints
â Efficiency constraints
⢠Time
⢠Power
â Time to completion
â Developer skills
⢠Extremes
â All that matters is to get to the market first!
â If the program fails, people die
â A 50% overhead implies the need for another $50M server farm
Stroustrup - C++11 Style - Feb'12 5
6. âMulti-paradigmâ is not good enough
These styles were never meant to be disjoint:
⢠C style
â functions and structures
â Typically lots of macros, void*, and casts
⢠C++85 style (aka âC with Classesâ)
â classes, class hierarchies, and virtual functions
⢠âTrue OOâ style
â Just class hierarchies
â Often lots of casts and macros
⢠Generic C++
â Everything is a template
Stroustrup - C++11 Style - Feb'12 6
7. What we want
⢠Easy to understand
â For humans and tools
â correctness, maintainability
⢠Modularity
â Well-specified interfaces
â Well-defined error-handling strategy
⢠Effective Resource management
â Memory, locks, files, âŚ
⢠Thread safety
â Unless specifically not
⢠Efficient
â Compact data structures
â Obvious algorithmic structure
⢠Portable
â Unless specifically not
Stroustrup - C++11 Style - Feb'12 7
8. What we want
⢠A synthesis
â And integrated set of features
â C++11 is a significant improvement
⢠Articulated guidelines for use
â What I call âstyleâ
Stroustrup - C++11 Style - Feb'12 8
9. Overview
⢠Ghastly style
â qsort() example
⢠Type-rich Programming
â Interfaces
â SI example
⢠Resources and errors
â RAII
â Resource handles and pointers
â Move semantics
⢠Compact data structures
â List vs. vector
â Vector of point
⢠Simplify control structure
â Algorithms, lambdas
⢠Low-level != efficient
⢠Type-safe concurrency
â Threads, async(), and futures
B. Stroustrup: Software Development for Infrastructure. IEEE Computer, January 2012
Stroustrup - C++11 Style - Feb'12 9
10. ISO C++11
⢠This is a talk about how to use C++ well
â In particular, ISO C++11
â C++ features as a whole support programming style
⢠This is not a talk about the new C++11 features
â I use those where appropriate
â My C++11 FAQ lists the new features
⢠Most C++11 features are already shipping
â E.g. Clang, GCC, and Microsoft C++
(the order is alphabetical ď)
⢠The C++11 standard library is shipping
â E.g. Boost, Clang, GCC, Microsoft C++
Stroustrup - C++11 Style - Feb'12 10
11. Ghastly Style
void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
void f(char* arr, int m, double* darr, int n)
{
qsort(arr, m, sizeof(char *), cmpstringp);
qsort(darr, n, sizeof(double), compare_double);
}
Stroustrup - C++11 Style - Feb'12 11
Memory to be sorted
Number of elements in memory
Number of bytes in an element
Element comparison function
âItâ doesnât know how to compare doubles?
âItâ doesnât know the size of a double?
âItâ doesnât know the number of elements?
12. Ghastly Style
void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
static int cmpstringp(const void *p1, const void *p2)
{ /* The actual arguments to this function are "pointers to pointers to char */
return strcmp(* (char * const *) p1, * (char * const *) p2);
}
static int compare_double(const void *p1, const void *p2)
{
double p0 = *(double*)p;
double q0 = *(double*)q;
if (p0 > q0) return 1;
if (p0 < q0) return -1;
return 0;
}
Stroustrup - C++11 Style - Feb'12 12
Throw away useful type information
Use inefficient indirect function call
Prevent inlining
13. Ghastly Style
⢠qsort() implementation details
â Note: I looked for implementations of qsort() on the web, but most of what I found were
âeducational fakesâ
/* Byte-wise swap two items of size SIZE. */
#define SWAP(a, b, size) do { register size_t __size = (size); register char *__a = (a), *__b = (b); do { char __tmp =
*__a; *__a++ = *__b; *__b++ = __tmp; } while (--__size > 0); } while (0)
/* ⌠*/
char *mid = lo + size * ((hi - lo) / size >> 1);
if ((*cmp) ((void *) mid, (void *) lo) < 0) SWAP (mid, lo, size);
if ((*cmp) ((void *) hi, (void *) mid) < 0) SWAP (mid, hi, size); else goto jump_over;
if ((*cmp) ((void *) mid, (void *) lo) < 0) SWAP (mid, lo, size);
jump_over:;
Stroustrup - C++11 Style - Feb'12 13
Swap bytes (POD only)
Lots of byte address manipulation
Lots of indirect function calls
14. Unfair? No!
⢠I didnât make up that example
â it is repeatedly offered as an example of good code (for decades)
â qsort() is a popular ISO C standard-library function
â That qsort() code is readable compared to most low-level C/C++ code
⢠The style is not uncommon in production code
â Teaching and academic versions often simplify to protect the innocent (fraud?)
⢠I see much worse on bulletin boards
â Have a look, and cry
⢠Many students aim for that level of code
â âfor efficiencyâ
â because it is cool (their idols does/did it!)
⢠Itâs not just a C/C++ problem/style
â Though I see C and C-style teaching as the source of the problem
Stroustrup - C++11 Style - Feb'12 14
15. Does it matter? Yes!
⢠Bad style is the #1 problem in real-world C++ code
â Makes progress relatively easy
â Only relatively: bad code breeds more bad code
⢠Lack of focus on style is the #1 problem in C++ teaching
â A âquick hackâ is usually the quickest short-term solution
⢠Faster than thinking about âdesignâ
â âTheyâ typically teach poor style
â Many are self-taught
⢠Take advice from
â Decades old books
â Other novices
⢠Imitate
â Other languages
â Bad old code
Stroustrup - C++11 Style - Feb'12 15
16. So what do I want?
⢠Simple interfaces
void sort(Container&); // for any container (e.g. vector, list, array)
// I canât quite get this is in C++ (but close)
⢠Simple calls
vector<string> vs;
// âŚ
sort(vs); // this, I can do
⢠Uncompromising performance
â Done: std::sort() beats qsort() by large factors (not just a few percent)
⢠No static type violations
â Done
⢠No resource leaks
â Done (without a garbage collector)
Stroustrup - C++11 Style - Feb'12 16
19. SI Units
⢠Units are effective and simple:
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
⢠They are also almost never used in programs
â General-purpose languages generally donât directly support units
â Run-time checking is far too costly
Stroustrup - C++11 Style - Feb'12 19
20. SI Units
⢠We can define Units to be handled at compile time:
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
Stroustrup - C++11 Style - Feb'12 20
21. SI Units
⢠We have had libraries like that for a decade
â but people never used them:
Speed sp1 = Value<1,0,0> (100)/ Value<0,0,1> (9.8); // very explicit
Speed sp1 = Value<M> (100)/ Value<S> (9.8); // use a shorthand notation
Speed sp1 = Meters(100)/Seconds(9.8); // abbreviate further still
Speed sp1 = M(100)/S(9.8); // this is getting cryptic
⢠Notation matters.
Stroustrup - C++11 Style - Feb'12 21
22. SI Units
⢠So, improve notation using user-defined literals:
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by âsâ
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by âs2â
{
return Value<Second2> (d);
}
Stroustrup - C++11 Style - Feb'12 22
23. SI Units
⢠Units are effective and simple:
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
⢠and essentially free (in C++11)
â Compile-time only
â No run-time overheads
Stroustrup - C++11 Style - Feb'12 23
24. Style
⢠Keep interfaces strongly typed
â Avoid very general types in interfaces, e.g.,
⢠int, double, âŚ
⢠Object, âŚ
Because such types can represent just about anything
â Checking of trivial types find only trivial errors
â Use precisely specified interfaces
Stroustrup - C++11 Style - Feb'12 24
26. 26
Resources and Errors
// unsafe, naĂŻve use:
void f(const char* p)
{
FILE* f = fopen(p,"r"); // acquire
// use f
fclose(f); // release
}
Stroustrup - C++11 Style - Feb'12
27. 27
Resources and Errors
// naĂŻve fix:
void f(const char* p)
{
FILE* f = 0;
try {
f = fopen(p, "r");
// use f
}
catch (âŚ) { // handle every exception
if (f) fclose(f);
throw;
}
if (f) fclose(f);
}
Stroustrup - C++11 Style - Feb'12
28. 28
RAII (Resource Acquisition Is Initialization)
// use an object to represent a resource
class File_handle { // belongs in some support library
FILE* p;
public:
File_handle(const char* pp, const char* r)
{ p = fopen(pp,r); if (p==0) throw File_error{pp,r}; }
File_handle(const string& s, const char* r)
{ p = fopen(s.c_str(),r); if (p==0) throw File_error{s,r}; }
~File_handle() { fclose(p); } // destructor
// copy operations
// access functions
};
void f(string s)
{
File_handle fh {s, "râ};
// use fh
}
Stroustrup - C++11 Style - Feb'12
29. RAII
⢠For all resources
â Memory (done by std::string, std::vector, std::map, âŚ)
â Locks (e.g. std::unique_lock), files (e.g. std::fstream), sockets, threads (e.g. std::thread), âŚ
std::mutex m; // a resource
int sh; // shared data
void f()
{
// âŚ
std::unique_lock lck {m}; // grab (acquire) the mutex
sh+=1; // manipulate shared data
} // implicitly release the mutex
Stroustrup - C++11 Style - Feb'12 29
30. Resource Handles and Pointers
⢠Many (most?) uses of pointers in local scope are not exception safe
void f(int n, int x)
{
Gadget* p = new Gadget{n}; // look Iâm a java programmer! ď
// âŚ
if (x<100) throw std::run_time_error{âWeird!â}; // leak
if (x<200) return; // leak
// âŚ
delete p; // and I want my garbage collector! ď
}
â No âNaked Newâ!
â But, why use a ârawâ pointer?
Stroustrup - C++11 Style - Feb'12 30
31. Resource Handles and Pointers
⢠A std::shared_ptr releases its object at when the last shared_ptr to it is destroyed
void f(int n, int x)
{
shared_ptr<Gadget> p = new Gadget{n}; // manage that pointer!
// âŚ
if (x<100) throw std::run_time_error{âWeird!â}; // no leak
if (x<200) return; // no leak
// âŚ
}
â But why use a shared_ptr?
â Iâm not sharing anything.
Stroustrup - C++11 Style - Feb'12 31
32. Resource Handles and Pointers
⢠A std::unique_ptr releases its object at when the unique_ptr is destroyed
void f(int n, int x)
{
unique_ptr<Gadget> p = new Gadget{n};
// âŚ
if (x<100) throw std::run_time_error{âWeird!â}; // no leak
if (x<200) return; // no leak
// âŚ
}
Stroustrup - C++11 Style - Feb'12 32
⢠But why use any kind of pointer ?
⢠Iâm not passing anything around.
33. Resource Handles and Pointers
⢠But why use a pointer at all?
⢠If you can, just use a scoped variable
void f(int n, int x)
{
Gadget g {n};
// âŚ
if (x<100) throw std::run_time_error{âWeird!â}; // no leak
if (x<200) return; // no leak
// âŚ
}
Stroustrup - C++11 Style - Feb'12 33
34. Resource Management Style
⢠Prefer classes where the resource management is part of their fundamental semantics
â E.g., std::vector, std::ostream, std::thread, âŚ
⢠Use âsmart pointersâ to address the problems of premature destruction and leaks
â std::unique_ptr for (unique) ownership
⢠Zero cost (time and space)
â std::shared_ptr for shared ownership
⢠Maintains a use count
â But they are still pointers
⢠âany pointer is a potential race condition â even in a single threaded programâ
Stroustrup - C++11 Style - Feb'12 34
35. How to move a resource
⢠Common problem:
â How to get a lot of data cheaply out of a function
⢠Idea #1:
â Return a pointer to a newâd object
Matrix* operator+(const Matrix&, const Matrix&);
Matrix& res = *(a+b); // ugly! (unacceptable)
â Who does the delete?
⢠there is no good general answer
Stroustrup - C++11 Style - Feb'12 35
36. How to move a resource
⢠Common problem:
â How to get a lot of data cheaply out of a function
⢠Idea #2
â Return a reference to a newâd object
Matrix& operator+(const Matrix&, const Matrix&);
Matrix res = a+b; // looks right, but âŚ
â Who does the delete?
⢠What delete? I donât see any pointers.
⢠there is no good general answer
Stroustrup - C++11 Style - Feb'12 36
37. How to move a resource
⢠Common problem:
â How to get a lot of data cheaply out of a function
⢠Idea #3
â Pass an reference to a result object
void operator+(const Matrix&, const Matrix&, Matrix& result);
Matrix res = a+b; // Oops, doesnât work for operators
Matrix res2;
operator+(a,b,res2); // Ugly!
â We are regressing towards assembly code
Stroustrup - C++11 Style - Feb'12 37
38. How to move a resource
⢠Common problem:
â How to get a lot of data cheaply out of a function
⢠Idea #4
â Return a Matrix
Matrix operator+(const Matrix&, const Matrix&);
Matrix res = a+b;
⢠Copy?
â expensive
⢠Use some pre-allocated âresult stackâ of Matrixes
â A brittle hack
⢠Move the Matrix out
â donât copy; âsteal the representationâ
â Directly supported in C++11 through move constructors
Stroustrup - C++11 Style - Feb'12 38
39. Move semantics
⢠Return a Matrix
Matrix operator+(const Matrix& a, const Matrix& b)
{
Matrix r;
// copy a[i]+b[i] into r[i] for each i
return r;
}
Matrix res = a+b;
⢠Define move a constructor for Matrix
â donât copy; âsteal the representationâ
Stroustrup - C++11 Style - Feb'12 39
âŚâŚ..
res:
r:
40. Move semantics
⢠Direct support in C++11: Move constructor
class Matrix {
Representation rep;
// âŚ
Matrix(Matrix&& a) // move constructor
{
rep = a.rep; // *this gets aâs elements
a.rep = {}; // a becomes the empty Matrix
}
};
Matrix res = a+b;
Stroustrup - C++11 Style - Feb'12 40
âŚâŚ..
res:
r:
41. Move semantics
⢠All the standard-library containers have move constructors and move assignments
⢠vector
⢠list
⢠forward_list (singly-linked list)
⢠map
⢠unordered_map (hash table)
⢠set
⢠âŚ
⢠string
⢠Not std::array
Stroustrup - C++11 Style - Feb'12 41
42. Style
⢠No naked pointers
â Keep them inside functions and classes
â Keep arrays out of interfaces (prefer containers)
â Pointers are implementation-level artifacts
â A pointer in a function should not represent ownership
â Always consider std::unique_ptr and sometimes std::shared_ptr
⢠No naked new or delete
â They belong in implementations and as arguments to resource handles
⢠Return objects âby-valueâ (using move rather than copy)
â Donât fiddle with pointer, references, or reference arguments for return values
Stroustrup - C++11 Style - Feb'12 42
43. Use compact data
⢠Vector vs. list
⢠Object layout
Stroustrup - C++11 Style - Feb'12 43
44. Vector vs. List
⢠Generate N random integers and insert them into a sequence so that each is
inserted in its proper position in the numerical order. 5 1 4 2 gives:
â 5
â 1 5
â 1 4 5
â 1 2 4 5
⢠Remove elements one at a time by picking a random position in the sequence and
removing the element there. Positions 1 2 0 0 gives
â 1 2 4 5
â 1 4 5
â 1 4
â 4
⢠For which N is it better to use a linked list than a vector (or an array) to represent
the sequence?
Stroustrup - C++11 Style - Feb'12 44
45. Vector vs. List
⢠Vector beats list massively for insertion and deletion
â For small elements and relatively small numbers (up to 500,000 on my machine)
â Your mileage will vary Stroustrup - C++11 Style - Feb'12 45
0
500
1000
1500
2000
2500
3000
3500
4000
4500
5000
1 2 3 4 5
Seconds
sequence test
vector
list
preallocated list
*100,000 elements
46. Vector vs. List
⢠Find the insertion point
â Linear search
â Vector could use binary search, but I did not
⢠Insert
â List re-links
â Vector moves on average n/2 elements
⢠Find the deletion point
â Linear search
â Vector could use direct access, but I did not
⢠delete
â List re-links
â Vector moves on average n/2 elements
⢠Allocation
â List does N allocations and N deallocations
â The optimized/preallocated list do no allocations or dealloations
â Vector does approximately log2(N) allocations and log2(N) deallocations
â The optimized list does 1 allocation and 1 deallocation
Stroustrup - C++11 Style - Feb'12 46
This completely dominates
47. Vector vs. List
⢠The amount of memory used differ dramatically
â List uses 4+ words per element
⢠it will be worse for 64-bit architectures
⢠100,000 list elements take up 6.4MB or more (but I have Gigabytes!?)
â Vector uses 1 word per element
⢠100,000 list elements take up 1.6MB or more
⢠Memory access is relatively slow
â Caches, pipelines, etc.
â 200 to 500 instructions per memory access
â Unpredictable memory access gives many more cache misses
⢠Implications:
â Donât store data unnecessarily.
â Keep data compact.
â Access memory in a predictable manner.
Stroustrup - C++11 Style - Feb'12 47
50. Algorithms vs. âCodeâ
⢠Problem: drag item to an insertion point
⢠Original solution (after cleanup and simplification):
â 25 lines of code
⢠one loop
⢠three tests
⢠14 function calls
⢠Messy code
â Is it correct?
⢠who knows? try lots of testing
â Is it maintainable?
⢠Probably not, since it is hard to understand
â Is it usable elsewhere?
⢠No, itâs completely hand-crafted to the details of the problem
⢠The author requested a review
â Professionalism!
Stroustrup - C++11 Style - Feb'12 50
51. Algorithms vs. âCodeâ
⢠Surprise!
â it was a simple find_if followed by moving the item
void drag_item_to(Vector& v, Vector::iterator source, Coordinate p)
{
Vector::iterator dest = find_if(v.begin(), v.end(), contains(p)); // find the insertion point
if (source < dest)
rotate(source, source+1, dest); // from before insertion point
else
rotate(dest, source, source+1); // from after insertion point
}
⢠Itâs comprehensible (maintainable), but still special purpose
â Vector and Coordinate are application specific
Stroustrup - C++11 Style - Feb'12 51
52. Algorithms vs. âCodeâ
⢠Why move only one item?
â Some user interfaces allow you to select many
template < typename Iter, typename Predicate>
pair<Iter, Iter> gather(Iter first, Iter last, Iter p, Predicate pred)
// move elements for which pred() is true to the insertion point p
{
return make_pair(
stable_partition(first, p, !bind(pred, _1)), // from before insertion point
stable_partition(p, last, bind(pred, _1)) // from after insertion point
);
}
⢠Shorter, simpler, faster, general (usable in many contexts)
â No loops and no tests
Stroustrup - C++11 Style - Feb'12 52
53. Style
⢠Focus on algorithms
â Consider generality and re-use
⢠Consider large functions suspect
⢠Consider complicated control structures suspect
Stroustrup - C++11 Style - Feb'12 53
54. Stay high level
⢠When you can
⢠Most of the time
Stroustrup - C++11 Style - Feb'12 54
55. Low-level != efficient
⢠Language features + compiler + optimizer deliver performance
â You can afford to use libraries of algorithms and types
â for_each()+lambda vs. for-loop
⢠Examples like these give identical performance on several compilers:
sum = 0;
for(vector<int>::size_type i=0; i<v.size(); ++i) // conventional loop
sum += v[i];
sum = 0;
for_each(v.begin(),v.end(), // algorithm + lambda
[&sum](int x) {sum += x; });
Stroustrup - C++11 Style - Feb'12 55
56. Low-level != efficient
⢠Language features + compiler + optimizer deliver performance
â sort() vs. qsort()
â Roughly : C is 2.5 times slower than C++
⢠Your mileage will wary
⢠Reasons:
â Type safety
⢠Transmits more information to the optimizer
⢠also improves optimization, e.g. type-bases anti-aliasing
â Inlining
⢠Observations
â Performance of traditional C-style and OO code is roughly equal
â Results vary based on compilers and library implementations
⢠But sort() is typical
Stroustrup - C++11 Style - Feb'12 56
57. Low-level != efficient
⢠Donât lower your level of abstraction without good reason
⢠Low-level implies
â More code
â More bugs
â Higher maintenance costs
Stroustrup - C++11 Style - Feb'12 57
58. Inheritance
Stroustrup - C++11 Style - Feb'12 58
⢠Use it
â When the domain concepts are hierarchical
â When there is a need for run-time selection among hierarchically ordered alternatives
⢠Warning:
â Inheritance has been seriously and systematically overused and misused
⢠âWhen your only tool is a hammer everything looks like a nailâ
60. Type-Safe Concurrency
⢠Programming concurrent systems is hard
â We need all the help we can get
â C++11 offers type-safe programming at the threads-and-locks level
â Type safety is hugely important
⢠threads-and-locks
â is an unfortunately low level of abstraction
â is necessary for current systems programming
⢠Thatâs what the operating systems offer
â presents an abstraction of the hardware to the programmer
â can be the basis of other concurrency abstractions
Stroustrup - C++11 Style - Feb'12 60
61. Threads
void f(vector<double>&); // function
struct F { // function object
vector<double>& v;
F(vector<double>& vv) :v{vv} { }
void operator()();
};
void code(vector<double>& vec1, vector<double>& vec2)
{
std::thread t1 {f,vec1}; // run f(vec1) on a separate thread
std::thread t2 {F{vec2}}; // run F{vec2}() on a separate thread
t1.join();
t2.join();
// use vec1 and vec2
}
Stroustrup - C++11 Style - Feb'12 61
62. Thread â pass argument and result
double* f(const vector<double>& v); // read from v return result
double* g(const vector<double>& v); // read from v return result
void user(const vector<double>& some_vec) // note: const
{
double res1, res2;
thread t1 {[&]{ res1 = f(some_vec); }}; // lambda: leave result in res1
thread t2 {[&]{ res2 = g(some_vec); }}; // lambda: leave result in res2
// âŚ
t1.join();
t2.join();
cout << res1 << ' ' << res2 << 'n';
}
Stroustrup - C++11 Style - Feb'12 62
63. async() â pass argument and return result
double* f(const vector<double>& v); // read from v return result
double* g(const vector<double>& v); // read from v return result
void user(const vector<double>& some_vec) // note: const
{
auto res1 = async(f,some_vec);
auto res2 = async(g,some_vec);
// âŚ
cout << *res1.get() << ' ' << *res2.get() << 'n'; // futures
}
⢠Much more elegant than the explicit thread version
â And most often faster
Stroustrup - C++11 Style - Feb'12 63
64. C++ Style
⢠Practice type-rich programming
â Focus on interfaces
â Simple classes are cheap â use lots of those
â Avoid over-general interfaces
⢠Integrate Resource Management and Error Handling
â By default, use exceptions and RAII
â Prefer move to complicated pointer use
⢠Use compact data structures
â By default, use std::vector
⢠Prefer algorithms to ârandom codeâ
⢠Build and use libraries
â Rely on type-safe concurrency
â By default, start with the ISO C++ standard libraryStroustrup - C++11 Style - Feb'12 64