Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting long to int?

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract: A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. An example cited from §15.26.2 […] the following code is … Read more

Template assignment operator overloading mystery

Why does assigning d to c not use the const overloaded assignment operator provided? The implicitly-declared copy assignment operator, which is declared as follows, is still generated: Wrapper& operator=(const Wrapper&); An operator template does not suppress generation of the implicitly-declared copy assignment operator. Since the argument (a const-qualified Wrapper) is an exact match for the … Read more

Should the Copy-and-Swap Idiom become the Copy-and-Move Idiom in C++11?

First of all, it is generally unnecessary to write a swap function in C++11 as long as your class is movable. The default swap will resort to moves: void swap(T& left, T& right) { T tmp(std::move(left)); left = std::move(right); right = std::move(tmp); } And that’s it, the elements are swapped. Second, based on this, the … Read more

What does an ampersand after this assignment operator mean?

It’s part of a feature allowing C++11 non-static member functions to differentiate between whether they are being called on an lvalues or rvalues. In the above case, the copy assignment operator being defaulted here can only be called on lvalues. This uses the rules for lvalue and rvalue reference bindings that are well established; this … Read more

Explicit copy constructor

The explicit copy constructor means that the copy constructor will not be called implicitly, which is what happens in the expression: CustomString s = CustomString(“test”); This expression literally means: create a temporary CustomString using the constructor that takes a const char*. Implicitly call the copy constructor of CustomString to copy from that temporary into s. … Read more