C++ 20 Features

Coroutines Coroutines are special functions that can have their execution suspended and resumed. To define a coroutine, the co_return, co_await, or co_yield keywords must be present in the function’s body. C++20’s coroutines are stackless; unless optimized out by the compiler, their state is allocated on the heap. Designated initializers Formatting library Combine the simplicity of printf with the type-safety of iostream. Uses braces…

Whether Should We Call std::move on std::unique_ptr

If a function takes a std::unique_ptr<>, that means it takes ownership of the argument. Callers need to use std::move() to indicate that they’re passing ownership if the object being passed is not a temporary: If a function returns a std::unique_ptr<>, that means the caller takes ownership of the returned object. Usage of std::move() while returning an object is only needed if the return type of…

Scoping and Friends in Nested Classes

Summary In this post, I will introduce the scoping in nested classes and how friend classes work here. Conclusion The rules are, As any member of its outer class, nested classes have access to all names (private, protected, etc) to which the outer class has access; however, outer classes have no special access to inner…

Custom Deleters of Shared & Unique Pointer

Summary In this post, I will introduce custom deleters when using C++ std::shared_ptr and std::unique_ptr. Conclusion Use the following snippets. Note the fourth case, where a unique_ptr with custom deleter will not pass the deleter to the shared_ptr when using release(). class OldThing { public: ~OldThing() { if (allocated_) { std::cout << "MEMORY LEAK!" <<…

Edge Cases of Namespace Pollution

Summary In the previous post, I introduced the rules of using directives (using namespace std) and using declarations (using std::vector). Generally speaking, the rules are good if there is no confliction, in which two using-declarations are the same. As a quick recap, using directives are forbidden. Since this directive makes all names from a namespace…

AddressSanitizer

Summary In this post, I will introduce a useful tool called AddressSanitizer. The motivation of it is that I have a debate with one of my colleagues about whether it is necessary to detect memory leaks in small projects. I was the one who persists to avoid memory issues though the program is small and…

Include Syntax

Summary In this post, I will introduce the different between #include "file" and #include <file> in C++. Conclusion #include <file> This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option. #include "file"…

In-Class Initialization Errors

Summary In this post, I will introduce some common compiling errors I used to see related to in-class initialization: Error: in-class initialization of static data member xxx of non-literal type; Error: ISO C++ forbids in-class initialization of non-const static member xxx; Conclusion As usual, I present the correct ways to do in-class initialization at the…

Include Guard V.S. #pragma once

Summary In this post, I will introduce the difference between include guard and #pragma directives in C++. Conclusion As usual, I will present the conclusion first. Include guard is the standard way to prevent multiple inclusion of the same header; #pragma directive is not required by C++ standard but now widely supported by most of…

Ways to Overload Default Order in C++’s STL

Summary In this post, I will introduce some methods to overload the default order in C++’s STL. Please refer to my other post if you are not familiar with Ordered Containers in C++. This post is a helpful reference when solving coding challenges. Conclusion You are giving a sequence of pairs, {{5, “five”}, {1, “one”},…

Thread Pool in C++

Summary In this post, I will introduce how to build a simple thread pool in C++. Conclusion The codes are from here. The thread pool only uses thread, mutex, and condition_variable. #include <thread> #include <mutex> #include <condition_variable> class ThreadPool; // our worker thread objects class Worker { public: Worker(ThreadPool &s) : pool(s) { } void…

Mutex in C++ and Java

Summary In this post, I will introduce the correct way to use mutex in C++, compared to Java. Conclusion Try not to use std::mutex directly. Use std::unique_lock, std::lock_guard, or std::scoped_lock (since C++17) to manage locking in a more exception-safe manner. Undefined behaviors will happen if a). A mutex is destroyed while still owned by any…

Virtual Functions, Constructors, and Destructors

Summary In this post, I will introduce rules related to constructors and destructors of classes which has virtual functions. Conclusions Golden Rule 1: Define a virtual destructor immediately Golden Rule 2: Do not invoke virtual functions from constructors or destructors Details In C++, Virtual functions allow for the choice of member function calls to be…

Override vs Overload

Summary In this post, I will introduce function override and function overload in C++, which are introduced by polymorphism in object oriented programming. Conclusion Overload Function overloadding achieves at compile time. It provides multiple definitions of the function by changing signature. Changing signatures includes changing number of parameters, change datatype of parameters. Note that return…

Class Template Definition and Declaration

Summary In this post. I will introduce class templates in C++. Especially, how do we declare a template which generates classes and how do we write definitions in separate source files. I will also dive deeper to present how class templates are compiled. Conclusion As usual, I present the conclusions first.Say the customer will use…

Install CUDA 10.1 and Driver 418

Summary In this post, I will introduce how to install the newest CUDA and corresponding Nvidia driver in Ubuntu 16.04. Details I want to use CUDA for neural network inference. But after I compile the executable files and run, it tells me driver not compatible with this version of CUDA. I have GTX 1060 and…

A Generic Project Structure in C++

Summary In this post, I will introduce a generic structure for C++ projects. Details A clean structure is the basis of a clean project. I simplify the full version and present a simpler but useful structure here. 1. bin: The output executables. 2. build: This folder contains all object files. 3. docs: Any notes, like…

Brief Introduction to Functors

Summary In this post, I will introduce function objects, also known as functors. Conclusion I provid the following snippets as a quick reference. See meeting-rooms-II for the problem details. /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int…

Namespace and Using

Summary In this post, I will introduce how to use "using" in C++, in other words, how to use an existing namespace. Conclusion As usual, I present the conclusion first. The followings are recommended ways which minimize name collision possibilities and maximize code clarity and writing convenience. See this post as well. For Headers Do…

Const, Pointers and References

Summary In this post, I will introduce const, * and & and their combinations. I also have similar posts discussed auto and &. Conclusion As usual, I present the golden rule first: “read from right to left”. In other words, the const-on-the-right style always puts the const on the right of what it constifies”. When…

References Versus Pointers

Summary In this post, I will discuss when to use References and when to use Pointers in C++. Conclusion As usual, I present the conclusion first. 1. If the varible can be nullptr, declare the varible as a pointer; 2. If the you want to re-assign the varible, declare the varible as a pointer; 3….

Class not Declared in Scope with .h Included

Summary I come across a compiling error, in which it says class A was not declared. However, I actually include A.h. Details After some research, I find out the bugs. In utils.h, I want to use some static member varible in class A and thus I include A.h. However, since utils.h acts as its name,…

Moving a Return Value is Easy

Summary In this post, we will discuss rvalue references and move semantics in C++11. Details Rvalue references and move semantics can be very complex, see this article. But the truth is that: the simplest is the best. It starts with three examples of returning values from functions. Read them and ask yourself which of them…

Search Files Under a Directory in C++

Summary In this post, I will introduce how to get a vector of files in a directory in C++. Instead of filesystem in boost or C++ 17, this method is purely based on C++ 11 and Unix platforms. Details The following codes are self-explained. // safe path join in unix-based system string path_join(const string& p1,…

Implement Java String APIs in C++

Summary It is another post related to String in C++. I will introduce some useful codes which implement APIs in Java String. Content String.startsWith() String.endsWith() String.toLowerCase() String.toUpperCase() String.trim() Detials 1. String.startsWith() We implement a.startsWith(b) of java using C++. bool starts_with(const string & a, const string & b) { return b == a.substr(0, b.size()); } int…

Lvalues and Rvalues in C++

Summary In this post, I will introduce lvalues and rvalues in C/C++. But I leave rvalue references and move semantics to the next post. Details Definition Lvalues: (locator value) represents an object that occupies some unique location in memory (has an address in some scope). Rvalues: not lvalues. Important points and examples 1. Rvalues can’t…

Delegating and Inheriting Constructors

Summary In this post, I will show delegating constructors introduced in C++ 11. Details I come across the codes below, and get confused about the systax. class Iterator { struct Data; Data* data; public: Iterator(const vector<int>& nums); Iterator(const Iterator& iter); virtual ~Iterator(); int next(); bool hasNext() const; }; class PeekingIterator : public Iterator { private:…

Change Object While Iterating It

Summary In this post we will discuss how to change object while iterating it. Details Say we have a map. unordered_map<char, int> char_counter ({{‘1’, 1}, {‘a’, 1}, {‘b’, 2}, {‘c’, 3}}); Now, we want to delete all elements whose value is 1. To delete an element using iterator we will use erase() function. But the…

Syntax Sugar in C++

Summary In this post, I will introduce some syntax sugar in C++. Content 1. Initializer List Constructor 2. Range in Container Construtor 3. Copy Constructor Details 1. Initializer List Constructor vector<int> vec({1,2,3,4,5}); unordered_map<char, int> char_counter ({{‘a’, 1}, {‘b’, 2}, {‘c’, 3}}); The syntax below is also legal. // use {} in vector vector<int> nums =…

String in C++

Summary In this post, I will introduce the string class in c++ STL. It covers useful APIs and some of my recommendations. 1. Split 2. Access 3. Comparison 4. Numeric-Conversions Details Split Thanks to this post, we present the conlusions for split first. 1. If you have access to boost, please do Solution 1. 2….

Bookmarks for C++

Summary In this post, I will show some useful websites for C++ learning. The post will be updated from time to time. URLs fluentcpp A great website focused on writing expressive C++ codes developed by Jonathan Boccara. Updated every Tuesday and Friday. Petr Zemek’s Blog A private website by Petr Zemek. Simplify C++ Another great…

Auto Type

Summary In this post, I will introduce auto, const auto, auto&, const auto&, auto&&, and const auto&&. Conclusion We provide the conclusion first. When you want a read-only access (generic or non-generic codes), use auto const &, which will give you a reference rather than a copy. When you want a read-write access in generic…

Common Mistakes in C++

Summary This post will be updated from time to time. The post contains some mistakes that I will make in work and study when coding in C++. Contents container.size() – 1 when the container is empty negative % positive ‘+’ does work in “C_String” remember to delete after new to_string(‘a’) signed integers compared to unsinged…

Auto in C++

Summary In this post, I will introduce auto and decltype in C++ 11. Why Auto In some situations, auto makes codes more readable. It will tell the compiler to deduce the type of a declared variable from the initialization expression. The details are complex. At present, we want to make codes correct, clean, and simple….

Ordered Containers

Summary In this post, I will introduce the map and priority_queue in c++ STL. Why Ordered Containers Unlike the easy version unordered_map, in map, key values are generally used to sort. Thanks to the binary search tree, map has good performance in search and erase elements $(log(n))$. Constructor The following codes are self-explained. // Example…