Is it possible to write a common function that handles both the copy constructor and copy assignment operator?

Yes. There are two common options. One – which is generally discouraged – is to call the operator= from the copy constructor explicitly: MyClass(const MyClass& other) { operator=(other); } However, providing a good operator= is a challenge when it comes to dealing with the old state and issues arising from self assignment. Also, all members … Read more

Can you write a common function that handles both the copy constructor and copy assignment operator?

Yes. There are two common options. One – which is generally discouraged – is to call the operator= from the copy constructor explicitly: MyClass(const MyClass& other) { operator=(other); } However, providing a good operator= is a challenge when it comes to dealing with the old state and issues arising from self assignment. Also, all members … Read more

Why can’t the default constructor be called with empty brackets?

Most vexing parse This is related to what is known as “C++’s most vexing parse”. Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration. Another instance of the same problem: std::ifstream ifs(“file.txt”); std::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>()); v is interpreted as a declaration of function with … Read more

C++11 rvalues and move semantics with return statement

First example std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> &&rval_ref = return_vector(); The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to … Read more

C++17 lambda capture *this

How is it useful? It’s useful when you need a copy of *this – for example, when *this itself is no longer valid by the time the lambda is evaluated. How is it different from capturing this? It makes a copy of the object, so that when the lambda is evaluated, its this pointer refers … Read more

tech