Search⌘ K

- Examples

Explore move and copy semantics in Modern C++ to understand how they affect memory management and performance. This lesson explains practical examples demonstrating value transfer with copy and move semantics, highlights the fallback behavior of copy semantic, and discusses performance implications in resource-limited environments.

Example 1

C++
// copyMoveSemantic.cpp
#include <iostream>
#include <string>
#include <utility>
int main(){
std::string str1{"ABCDEF"};
std::string str2;
std::cout << "\n";
// initial value
std::cout << "str1= " << str1 << std::endl;
std::cout << "str2= " << str2 << std::endl;
// copy semantic
str2= str1;
std::cout << "str2= str1;\n";
std::cout << "str1= " << str1 << std::endl;
std::cout << "str2= " << str2 << std::endl;
std::cout << "\n";
std::string str3;
// initial value
std::cout << "str1= " << str1 << std::endl;
std::cout << "str3= " << str3 << std::endl;
// move semantic
str3= std::move(str1);
std::cout << "str3= std::move(str1);\n";
std::cout << "str1= " << str1 << std::endl;
std::cout << "str3= " << str3 << std::endl;
std::cout << "\n";
}

Explanation

In the above example, we demonstrated how the value of str1 can be transferred to strings using two different methods: copy semantic and move semantic.

  • In line 18, we used the copy semantic, and the string "ABCDEF" is present in both str1 and str2. We can, therefore, say that the value has ...