Two weeks ago, I came across an interesting bug. The convert() function below returns 0x80000001 when p points to 0x01, 0x00, 0x00, 0x80, but the expected return value is 0x00000001 instead. int32_t convert(const uint8_t *restrict p) { uint32_t x = ( p[0] + 256...
Ctags is a source code indexing tool. With ctags, we can easily find the definitions of the classes, functions, and variables. According to my experiences, ctags can significantly reduce the time to browse the source code. In this post, I would like to give a brief introduction to ctags and...
C++11 introduced three new smart pointer class templates: std::unique_ptr, std::shared_ptr, and std::weak_ptr. These smart pointer class templates are designed to replace the old std::auto_ptr smart pointer, which is known to have some defect and deprecated now. In this post, I would like to give...
Today I have encountered a problem: Given that there are multiple equivalent keys in an instance of std::multimap, how could we list all of the corresponding values? For example: #include <map> #include <iostream> int main() { std::multimap<int, int> xs;...
It is a well-known idiom to define a virtual destructor for the classes with virtual functions. If we don't define a virtual destructor, then the base class destructor will be invoked when you are deleting the object through the base class pointer even if the object is an instance of derived...
I used to feel that the private inheritence is useless. Although we can implement the has-a semantics with private inheritence, it provides little benefits compared with object composition. Besides, in order to expose the privately inherited members to public, C++ introduced an awkward syntax,...
To sort the doubly linked list std::list, we can simply call the sort() member function. For example, #include <iostream> #include <list> int main() { std::list<int> xs{5, 4, 3, 2, 1}; xs.sort(); // Sort the std::list! for (auto &x : xs) { std::cout << x...
I used to believe that iterators will be invalidated after calling the member functions insert() or erase() of containers. Thus, I would adopt a conservative approach: Create a temporary container. Copy the elements which I would like to keep to the temporary container. Swap the container. For...