File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 오른값 참조에는 std: move 를, 보편 참조에는 std::forward를 사용하라
2
+
3
+ #### 보편 참조와 forward를 이용하여 중복적재를 피하자
4
+
5
+ ``` c++
6
+
7
+ // 중복적재
8
+ class Widget {
9
+ private:
10
+ std::string name;
11
+ public:
12
+ void setName(cont std::string& newName)
13
+ { name = newName; }
14
+ void setName(std::string&& newName)
15
+ { name = std::move(newName); }
16
+ std::string& getName()
17
+ { return name; }
18
+ };
19
+
20
+ // 보편 참조와 forward 사용
21
+ class Widget {
22
+ private:
23
+ std::string name;
24
+ public:
25
+ template<typename T >
26
+ void setName(T&& newName)
27
+ {
28
+ std::cout<<"call"<<"\n";
29
+ name = std::forward<T >(newName);
30
+ }
31
+ std::string& getName()
32
+ { return name; }
33
+ };
34
+
35
+ int main()
36
+ {
37
+ std::string n = std::string("lee");
38
+ Widget w;
39
+
40
+ w.setName(n);
41
+ std::cout<<w.getName()<<"\n";
42
+
43
+ w.setName(std::string("changsu"));
44
+ std::cout<<w.getName()<<"\n";
45
+ return 0 ;
46
+ }
47
+
48
+ changsu1.lee@VDBS1383:~ /work/test$ ./main
49
+ call
50
+ lee
51
+ call
52
+ changsu
53
+ ```
54
+
55
+
56
+
You can’t perform that action at this time.
0 commit comments