Prefer initializer list for variable initialization

Implicit conversion is a convenience that C++ offers to programmers. However, sometimes this can cause unexpected results. It is always a good rule of thumb to be explicit when expressing your intent. The following code snippet demonstrates how implicit conversion (both narrowing and widening) can be useful and can avoid casting between data types manually. #include<iostream> int main() { int num = 10.2; // Implicitly converts float to num which is fine at the cost of loosing precision float radius = 10; // Implicity converts int to float....

February 10, 2024 · 2 min · 290 words

Avoid Unintentional Copying in C++ Containers

C++ default semantics often involve copying, which can sometimes lead to unintended consequences. Let’s explore this through a practical example involving shared pointers. The Pitfall Consider the following scenario where we create a shared pointer to a set of strings: #include<iostream> #include<set> #include<memory> int main() { typedef std::set<std::string> STRINGSET; STRINGSET names = {"Tom", "Tim", "Sam"}; auto names_sptr = std::make_shared<STRINGSET>(names); { auto names_ptr_cpy = names_sptr; std::cout << "Share pointer use: " << names_sptr....

February 9, 2024 · 3 min · 463 words

Initialization is not assigment

In C++, initialization and assignment are distinct operations. Through the code snippet below, we will explore these differences. While examining the code, one might initially assume that IntWrapper’s constructor and destructor are called an equal number of times. However, this is not the case. IntWrapper is initialized once (through constructor invocation) but assigned multiple times to other variables through copying. For each IntWrapper object, whether created through initialization or assignment, there is a corresponding call to the destructor (typically)....

February 9, 2024 · 3 min · 432 words