Hi
It's been a while i'm learing C++ but still i have some issue with Move semantics
and some other stuff.
I wrote this class but i don't know why the Copy constructor
is getting called
and the output is a little strange to me, shouldn't the Move Constructor
gets called three times only? i don't know what i did wrong.
Also in the Move Connstructor
i could use Data(other.Data)
but in the Copy Constructor
i couldn't
i had to write a for
loop or use std::copy
, why?
I appreciate your answers.
Output
Move constructor is called!
Move constructor is called!
Copy constructor is called!
Move constructor is called!
Copy constructor is called!
Copy constructor is called!
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
class Foo
{
private:
std::size_t size;
int* Data;
public:
Foo(std::size_t length): size(length), Data(new int [length])
{}
//Copy Constructor
Foo(const Foo& other): size(other.size), Data(new int[other.size])
{
std::cout<<"Copy constructor is called!"<<std::endl;
std::copy(other.Data, other.Data + size, Data);
}
//Move Constructor
Foo(Foo&& other): size(other.size), Data(other.Data)
{
std::cout<<"Move constructor is called!"<<std::endl;
other.size=0;
other.Data = nullptr;
}
std::size_t retSize() const
{
return size;
}
~Foo()
{
delete [] Data;
size = 0;
}
};
int main ()
{
std::vector <Foo> vec;
vec.push_back(Foo(15));
vec.push_back(Foo(12));
vec.push_back(Foo(17));
return 0;
}