Tutorial by Examples

Move semantics are a way of moving one object to another in C++. For this, we empty the old object and place everything it had in the new object. For this, we must understand what an rvalue reference is. An rvalue reference (T&& where T is the object type) is not much different than a norma...
Say we have this code snippet. class A { public: int a; int b; A(const A &other) { this->a = other.a; this->b = other.b; } }; To create a copy constructor, that is, to make a function that copies an object and creates a new one, we norma...
Similarly to how we can assign a value to an object with an lvalue reference, copying it, we can also move the values from an object to another without constructing a new one. We call this move assignment. We move the values from one object to another existing object. For this, we will have to over...
C++11 introduced core language and standard library support for moving an object. The idea is that when an object o is a temporary and one wants a logical copy, then its safe to just pilfer o's resources, such as a dynamically allocated buffer, leaving o logically empty but still destructible and co...
You can move a container instead of copying it: void print(const std::vector<int>& vec) { for (auto&& val : vec) { std::cout << val << ", "; } std::cout << std::endl; } int main() { // initialize vec1 with 1, 2, 3, 4 and...
You can re-use a moved object: void consumingFunction(std::vector<int> vec) { // Some operations } int main() { // initialize vec with 1, 2, 3, 4 std::vector<int> vec{1, 2, 3, 4}; // Send the vector by move consumingFunction(std::move(vec)); // Here...

Page 1 of 1