- Examples
Some examples of copy and move semantics will be discussed in this lesson.
We'll cover the following...
Example 1
Press + to interact
// copyMoveSemantic.cpp#include <iostream>#include <string>#include <utility>int main(){std::string str1{"ABCDEF"};std::string str2;std::cout << "\n";// initial valuestd::cout << "str1= " << str1 << std::endl;std::cout << "str2= " << str2 << std::endl;// copy semanticstr2= 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 valuestd::cout << "str1= " << str1 << std::endl;std::cout << "str3= " << str3 << std::endl;// move semanticstr3= 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 bothstr1
and ...
Access this course and 1400+ top-rated courses and projects.