Created
September 4, 2016 15:27
-
-
Save dmh2000/e38ac4db05711adbac3f89aced2de6a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstdlib> | |
#include <cstring> | |
struct X { | |
private: | |
size_t m_len; | |
char *m_data; | |
public: | |
X() : m_len(0),m_data(nullptr) { | |
printf("default constructor\n"); | |
} | |
X(size_t len) : m_len(len),m_data(new char[len]) { | |
printf("init constructor\n"); | |
memset(m_data,0,m_len); | |
} | |
// copy constructor must make a copy of the object | |
// because it has a reference to something | |
// that belongs to the caller | |
X(const X &r) | |
{ | |
printf("copy constructor\n"); | |
m_len = r.m_len; | |
m_data = new char[m_len]; | |
memcpy(m_data,r.m_data,m_len); | |
} | |
// move constructor doesn't need to copy | |
// because it is given a reference to | |
// a temporary object that would be discarded anyway | |
X(X &&r) | |
{ | |
printf("move constructor\n"); | |
m_len = r.m_len; | |
m_data = r.m_data; | |
r.m_data = nullptr; | |
r.m_len = 0; | |
} | |
void print() | |
{ | |
printf("%llu\n",m_len); | |
} | |
}; | |
// a function that returns a temporary value | |
X makeX(size_t len) | |
{ | |
X x(len); | |
return x; | |
} | |
int main(int argc,char *argv[]) | |
{ | |
X a(makeX(10)); // move constructor, because temporary object can be discarded | |
X b(a); // copy constructor, because lvalue is persistent | |
X c; | |
a.print(); | |
b.print(); | |
c.print(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment