-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRef.cpp
More file actions
92 lines (78 loc) · 1.83 KB
/
Ref.cpp
File metadata and controls
92 lines (78 loc) · 1.83 KB
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
#include <cstring>
#include <iostream>
class dsString{
public:
size_t len_;
char* str_;
dsString();
~dsString();
dsString(const char *);
dsString(const dsString &);
dsString(dsString &&);
dsString& operator=(dsString&& s);
};
dsString::dsString(): str_(0), len_(0)
{
std::cout << "default constructor" << this << std::endl;
}
dsString::~dsString()
{
std::cout << "destructor:" << this << std::endl;
delete [] str_;
}
dsString& dsString::operator=(dsString&& s) // move assignment
{
std::cout << "move assignment" << this << std::endl;
str_ = s.str_;
len_ = s.len_;
s.str_ = 0;
s.len_ = 0;
return *this;
}
dsString::dsString(const char *str)
{
len_ = strlen(str);
str_ = new char(len_);
std::cout << "const char *str constructor " << this << std::endl ;
memcpy(str_, str, len_);
}
dsString::dsString(dsString &&s)
{
str_ = s.str_;
len_ = s.len_;
s.str_ = 0;
s.len_ = 0;
std::cout << "move constructor " << this << std::endl;
}
dsString::dsString(const dsString &s)
{
std::cout << "copy constructor " << this << std::endl;
len_ = strlen(s.str_);
str_ = new char(len_);
memcpy(str_, s.str_, s.len_);
}
void flvalue(dsString s)
{
std::cout << "flvalue s: " << s.str_ << std::endl;
}
void flvalueRef(dsString& s)
{
std::cout << "flvalueRef s: " << s.str_ << std::endl;
}
void fRvalueRef(dsString&& s)
{
std::cout << "fRvalueRef s: " << s.str_ << std::endl;
}
int main()
{
dsString s1{"s1"};
dsString s2{"s2"};
dsString s3{"s3"};
flvalue(s1);
flvalue(std::move(s1));
flvalueRef(s2);
//flvalueRef(std::move(s2)); cannot bind non-const lvalue reference to an rvalue
//fRvalueRef(s2); cannot bind rvalue reference to lvalue
fRvalueRef(std::move(s3));
return 0;
}