c++

move constructor

In some cases, object will be copied automatically:

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
class Mystring
{
private:
char* buffer;
public:
Mystring(const char* inistString) //Constructor
{
buffer = NULL;
cout << "Default constructor: creating new MyString" << endl;
if(initString != NULL)
{
buffer = new char(strlen(initString) + 1); //Allocating memory
strcpy(buffer, initString);

cout << "buffer points to: 0X"<<hex;
cout << (unsigned int*)buffer <<endl;
}
}

MyString(const MyString & copySource)//copy constructor
{
buffer = NULL;
cout << "Copy constructor: copying from MyString" << endl;
if(copySource.buffer != NULL)
{
//allocate own buffer
buffer = new char [strlen(copySource.buffer) + 1];

//deep copy from the source into local buffer
strcpy(buffer, copySource.buffer);
cout << "buffer points to: 0X" <<hex;
cout << (unsigned int*)buffer << endl;
}
}

~Mystring() //Destructor
{
cout << "invoking destructor, clearing up" << end;
if(buffer != NULL)
delete [] buffer;
}

int GetLength()
{
return strlen(buffer);
}

const char* GetString()
{
return buffer;
}
};

Mystring Copy(MyString & source) //func
{
MyString copyForReturn(source.GetString());//create copy
return copyForReturn;//reruen by value invokes copy constructor
}

int main()
{
MyString sayHello("Hello World");
MyString sayHelloAgain(Copy(sayHello));//invokes 2 times copy constructor

return 0;
}

When instantiating ‘sayHelloAgain’, that will invoke func ‘Copy(sayHello)’, and the func return a MyString by Value, therefore invokes copy constructor twice. But, the value returned exist a short period, and not aviliable outside of the expression. So, it reduced performance.

That’s why here comes the Move constructor:

1
2
3
4
5
6
7
8
9
//move constructor syntax:
MyString(MyString && movesorce)
{
if(movesource.buffer != NULL)
{
buffer = movesource.buffer; //take ownership
movesorce.buffer = NULL; //set the move source to NULL
}
}

This post will be update later.

Share