공부 기록을 남긴다.
lvalue rvalue zero copy
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | #include <iostream> #include <array> #include <vector> #include <string> class Cat { public:     void setName(std::string name)     {         mName = std::move(name);     }; private:     std::string mName; }; void storeByValue(std::string s) {     std::string b = s; } void storeByLRef(std::string& s) {     std::string b = s; } void storeByRRef(std::string&& s) {     //std::string b = s; // wrong!     std::string b = std::move(s); } void storeByRRef_const(const std::string&& s) {     // input을 const로 받으면 copy가 일어나게 된다     // visual studio 2019에서는 에러 발생     std::string b = std::move(s); } void fooV(int a) {     int b = a + 1; } void fooP(int* ap) {     int b = *ap + 1;     *ap = 100; } void fooR(const int &a) {     int b = a + 1;     //a = 100; // 에러(const a 이므로) } int main() {     int a = 0;     // a가 두번 생성됨     fooV(a);     // 사실 포인터와 레퍼런스로 넣어 주는 것은 똑같다.     // 표기의 차이임     fooP(&a);     fooR(a);     // 포인터를 꼭 써야 하는 경우가 아니면     // 레퍼런스를 사용하도록 한다     std::vector<int> vec;     int a1 = 1;     int a2 = 2;     vec.push_back(a1);     vec.push_back(a2);     std::string string_a = "abc";     storeByValue(string_a); // (two copy)abc 총 3번 생김(string_a, storeByValue에서 string_a,                             // string b = "abc" 에서 , 다 합치면 3번임     storeByLRef(string_a); // (one copy)abc 총 2번 생김 string_a abc 1번, b에서 abc 1번 총 두번     storeByRRef(std::move(string_a));     storeByRRef("abc"); // (zero copy)copy 한번도 안 일어남     //storeByRRef_const(string_a); // gcc에서는 compile 가능     std::string testa = "devwoong";     std::cout << "a: " << testa << std::endl;     std::string testb = std::move(testa);     std::cout << "b: " << testb << std::endl;     std::cout << "a: " << testa << std::endl; // std::move로 없어 짐     // std::move로 resource ownership을 다른 부분으로 옮겨 줌     Cat kitty;     std::string s = "kitty";     kitty.setName(s); // Copy 1번     kitty.setName("nabi"); // rvalue 전달 zero copy 발생!     return 0; } | 
'C' 카테고리의 다른 글
| c++ object memory alignment (0) | 2021.06.23 | 
|---|---|
| c++ copy elison, Retrun value optimization (0) | 2021.06.23 | 
| c++ heap memory space (0) | 2021.06.22 | 
| c++ stack 공간, class, struct, 타입별 메모리 사이즈 (0) | 2021.06.22 | 
| c++ extern static 기록 정리 (0) | 2021.06.22 |