I am getting the following errors when compiling this using g++ 5.7 and when I remove the explicit deceleration it compiles with no warning. but I would like to know why.
compile error message:
move_semantics.cpp: In function ‘MyString hello_world_return_copy()’:
move_semantics.cpp:44:9: error: no matching function for call to ‘MyString::MyString(MyString&)’
return s;
^
move_semantics.cpp: In function ‘MyString hello_world_return_move()’:
move_semantics.cpp:51:20: error: no matching function for call to ‘MyString::MyString(std::remove_reference<MyString&>::type)’
return std::move(s);
^
move_semantics.cpp: In function ‘MyString hello_world_return_statc()’:
move_semantics.cpp:57:33: error: no matching function for call to ‘MyString::MyString(MyString&)’
return static_cast<MyString&>(s);
^
move_semantics.cpp: In function ‘int main()’:
move_semantics.cpp:67:42: error: no matching function for call to ‘MyString::MyString(MyString)’
MyString temp = hello_world_return_copy();
source:
#include <string>
#include <iostream>
struct MyString {
explicit MyString(const char* input) {
std::cout << "Constructor called" << std::endl;
_str = std::string(input);
}
explicit MyString(const MyString& other) {
std::cout << "Copy constructor called" << std::endl;
_str = other._str;
}
explicit MyString(MyString& other) {
std::cout << "Copy constructor called" << std::endl;
_str = other._str;
}
~MyString() {
std::cout << "destructor called" << std::endl;
}
private:
std::string _str;
};
MyString hello_world_return_copy()
{
MyString s("hello world!");
return s;
}
MyString hello_world_return_move()
{
MyString s("hello world!");
// move takes an lvalue as argument and returns an rvalue
return std::move(s);
}
int main() {
MyString temp = hello_world_return_copy();
}
I am trying to experiment and learn more about move semantics, rvalues and etc. The weird thing is the compiler complains about not having a MyString::MyString(MyString&)
function though I do have one.
Aucun commentaire:
Enregistrer un commentaire