#ifndef V_H
#define V_H
class V
{
private:
int size;
int *array;
public:
//constructor
V(int s):size(s)
{
std::cout<<"Constructor ..."<<std::endl;
array = new int[size];
for(int i = 0; i < size; i++)
array[i] = 10*i;
std::cout<<"----End Constructor ..."<<std::endl;
}
//copy constructor
V(const V &right):size(right.size), array(size?new int [size]:nullptr)
{
std::cout<<"Copy Constructor ..."<<std::endl;
std::copy(right.array, right.array+size, array);
std::cout<<"----End Copy Constructor ..."<<std::endl;
}
//move constructor
V(V && right):size(0), array(nullptr)
{
std::cout<<"Move Constructor ..."<<std::endl;
size = right.size;
array = right.array;
right.size = 0;
right.array = nullptr;
std::cout<<"----End Move Constructor ..."<<std::endl;
}
int *getAddress() const {return array;}
int getSize() const {return size;}
void display() const
{
for(int i = 0; i < size; i++)
std::cout<<array[i]<<" ";
std::cout<<std::endl;
}
//copy assignment
const V& operator=(const V &right)
{
std::cout<<"Copy Assignment ..."<<size<<std::endl;
V temp(right);
std::swap(size, temp.size);
std::swap(array, temp.array);
std::cout<<"----End Assignment ..."<<std::endl;
return *this;
}
//move assignment
V & operator=(V&& right)
{
std::cout<<"Move Assignment ..."<<std::endl;
if(this != &right)
{
delete [] array;
array = 0;
size = 0;
size = right.size;
array = right.array;
right.size = 0;
right.array = nullptr;
}
std::cout<<"----End Move Assignment ..."<<std::endl;
return *this;
}
~V()
{
std::cout<<"Destructor ..."<<size<<std::endl;
delete array;
array = 0;
size = 0;
}
};
#endif
#include <iostream>
#include "V.h"
V getObject()
{
std::cout<<"Inside function ..."<<std::endl;
//call constructor
V v(10);
std::cout<<"Return from function ..."<<std::endl;
return v;
}
int main(int argc, char *argv[])
{
//call constructor
std::cout<<"---------------Call Constructor-----------"<<std::endl;
V v1(20);
//call copy constructor
std::cout<<"---------------Call Copy Constructor--------"<<std::endl;
V v2(v1);
//V v2 = v1;
//call assignment constructor
std::cout<<"---------------Call Assignment Constructor---------"<<std::endl;
V v3(40);
v3 = v1;
//call assignment
//if no move assignment, assignment constructor will be called
std::cout<<"-------------Call Move Assignment--------------"<<std::endl;
v2 = getObject();
//v2 = std::move(v3);
std::cout<<"-------------Call Move Constructor---------------"<<std::endl;
V v4(std::move(getObject()));
//V v5(getObject());//object created by getObject() will be assigned to v5 directly, no move constructor will be called
//V v5 = getObject();
V v6(std::move(v1));//v1 is empty
return 0;
}
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
std::string str = "Hello";
//call move assignment
std::string str2;
str2 = std::move(str);
//call move constructor
//std::string str2 = std::move(str);
std::cout<<"Str 1: "<<str<<std::endl;//str is empty
std::cout<<"Str 2: "<<str2<<std::endl;
return 0;
}