mirror of
https://github.com/changkun/modern-cpp-tutorial.git
synced 2025-12-17 12:44:40 +03:00
31
code/3/3.6.move.semantics.cpp
Normal file
31
code/3/3.6.move.semantics.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// 3.5.move.semantics.cpp
|
||||
// modern c++ tutorial
|
||||
//
|
||||
// created by changkun at changkun.de
|
||||
// https://github.com/changkun/modern-cpp-tutorial
|
||||
//
|
||||
|
||||
#include <iostream> // std::cout
|
||||
#include <utility> // std::move
|
||||
#include <vector> // std::vector
|
||||
#include <string> // std::string
|
||||
|
||||
int main() {
|
||||
|
||||
std::string str = "Hello world.";
|
||||
std::vector<std::string> v;
|
||||
|
||||
// use push_back(const T&), copy
|
||||
v.push_back(str);
|
||||
// "str: Hello world."
|
||||
std::cout << "str: " << str << std::endl;
|
||||
|
||||
// use push_back(const T&&), no copy
|
||||
// the string will be moved to vector, and therefore std::move can reduce copy cost
|
||||
v.push_back(std::move(str));
|
||||
// str is empty now
|
||||
std::cout << "str: " << str << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user