Download presentation
Presentation is loading. Please wait.
1
Modern C++ Pitfalls Mihai Todor 09.04.2015
Disclaimer: This presentation is focused on C++11/14 features and assumes a basic understanding of C++
2
What are we trying to achieve?
Rigurous compile-time checks Compile once, run many times We have to be realistic, though Javascript doesn’t try very hard Why does parseInt(1/0, 19) return 18?* *
3
Recap I Some funky template magic Move semantics Auto nullptr
Range-based for loops override and final Strongly-typed enums Lambdas Explicitly defaulted and deleted functions Smart pointers Some funky template magic
4
Recap II Template factory with type detection
Template factory with method detection There are some issues in these two examples!
5
decltype and std::declval
Standardized version of typeof Queries the return type of an expression Doesn’t evaluate its operand Perfect return type forwarding (C++14)* std::declval Obtains the type of an expression in an unevaluated context (inside decltype) Access to member functions without invoking constructors *
6
Let’s play with references*
std::remove_reference std::add_lvalue_reference std::add_rvalue_reference std::is_reference std::is_lvalue_reference std::is_rvalue_reference *See the <type_traits> header:
7
But why do we need to use std::declval anyway?
class Object {}; template <typename T> auto ReturnInput(T &input) -> decltype(T()) { return input; } … Object obj; Can ReturnInput take obj as a parameter?
8
But why do we need to use std::declval anyway? – Part II
Object has a private default constructor and the expression inside declval needs to be valid! This will work: auto ReturnInput(T &input) -> decltype(std::declval<T>())
9
SFINAE Substitution Failure Is Not An Error
Applies during overload resolution of function templates Expression SFINAE (C++11) Removes functions from the list of overloads if the expression inside decltype is not valid* *
10
Why did I show you all of this?
Let’s get back to TemplateFactoryWithMethodDetection.cpp A real use case for method detection can be found here:
11
Default Template Arguments for Metod Templates
We can have template methods inside template classes Before C++11, they could not have default template arguments More details on StackOverflow* *
12
Range-based for loops References to certain contaier objects can be problematic
13
<algorithm> Pitfalls
std::lower_bound std::upper_bound std::equal_range std::binary_search They work on any sorted sequence container, including std::list! std::advance has O(N) complexity for non-random access* Detailed information here: *
14
make_shared and make_unique
Create new instances of shared_ptr and unique_ptr They address multiple issues: Improved performance Exception safety
15
See my activity on StackOverflow:
stackoverflow.com/users/ /mihai-todor Follow me on: Linkedin: Github: github.com/mihaitodor
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.