Is it correct that the move constructor is never used, unless I use std::move()
? I once heard that it would be optimized so that a value that is not used anymore in the current scope would be moved instead of copied to make the code more efficient. However, this seems not to always work:
//One
void tester() {
Test t(5);
Test m(t);
}
//Two
void tester() {
Test t(5);
std::vector<Test> v;
v.push_back(t);
}
//Three
void takeTest(Test t) {
//Do nothing
}
void tester() {
Test t(5);
takeTest(t);
}
All those snippets seem to use the copy constructor. I have made Test
as following, to see which constructors are being used. Feel free to point out any errors/bad practices in this code:
class Test{
public:
int i;
Test(int inp) : i(inp){
std::cout << "Constructor" << std::endl;
}
~Test() {
std::cout << "Destructor" << std::endl;
}
Test(const Test& other) {
this->i = other.i+10000;
std::cout << "Copy" << std::endl;
}
Test(Test&& other) noexcept {
this->i = other.i+10000;
std::cout << "Move" << std::endl;
}
Test& operator=(const Test& other) {
this->i = other.i+100;
std::cout << "Assignment" << std::endl;
return *this;
}
Test& operator=(Test&& other) noexcept {
this->i = other.i+1000;
std::cout << "Move" << std::endl;
return *this;
}
};
Aucun commentaire:
Enregistrer un commentaire