I am currently reading about the move constructor. I have written the following code
#include <iostream>
#include <cstring>
class foo
{
private:
std::string str_member;
char* char_member ;
public:
foo()
{
std::cout << "Regular constructor \n";
}
foo(const foo& r)
{
std::cout << "Copy Constructor \n";
//Make copies of the contents
char_member = new char[strlen(r.char_member)+1];
strcpy(char_member,r.char_member);
str_member = r.str_member;
}
foo& operator=(const foo& r)
{
//Do somestuff
std::cout << "Copy Assignment operator \n";
}
//Move Special Member functions
//Move constructor
foo(foo&& r)
{
//Do somestuff
std::cout << "move constructor \n";
}
//Move Assigment operator
foo& operator=(foo&& r)
{
//Do some stuff
std::cout << "Move assignment operator";
}
};
//Some Method that returns an object by value
foo Mymethod()
{
foo d;
return d;
}
int main()
{
foo p(Mymethod());
std::cin.get();
}
Output is "Regular constructor".
Now the above class is simply a test class and does not really have the correct copy / assignment / move constructor or move assignment. I am currently only interested in understanding when the move constructor is called. According to my understanding when the function returns a move constructor should be called and then since an rvalue is returned another move constructor should be called.
I have read When Does Move Constructor get called? and aschepler states that:
A move constructor is called:
- [..]
- when throwing a function-local class object and the compiler doesn't eliminate the copy/move entirely
Why am I only getting a regular constructor.? I would appreciate it if someone could explain to me why my understanding is wrong. I believe that a move constructor should be called when object is returned from the method and then the move constructor of the foo p
should be called.