Skip to content

Instantly share code, notes, and snippets.

@ousttrue
Last active December 26, 2015 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ousttrue/7178535 to your computer and use it in GitHub Desktop.
Save ousttrue/7178535 to your computer and use it in GitHub Desktop.
move constructor test
#include <memory>
#include <iostream>
class RightKun
{
public:
RightKun()
{
std::cout << this << ":default constructor" << std::endl;
};
~RightKun()
{
std::cout << this << ":destructor" << std::endl;
}
RightKun(const RightKun &src)
{
std::cout << this << ":copy constructor: ";
*this=src;
}
RightKun &operator=(const RightKun &src)
{
std::cout << "left value operator= " << &src << std::endl;
return *this;
}
RightKun(RightKun &&src)
{
std::cout << this << ":move constructor: ";
*this=std::move(src);
}
RightKun &operator=(RightKun &&src)
{
std::cout << "right value operator= " << &src << std::endl;
return *this;
}
};
int main()
{
{
std::cout << "[default]" << std::endl;
// default
RightKun r1;
// copy
RightKun r2=r1;
}
std::cout << std::endl;
{
auto create=[]()->RightKun
{
return RightKun();
};
std::cout << "[RVO]" << std::endl;
RightKun r=create();
}
std::cout << std::endl;
{
auto createNoRVO=[]()->RightKun
{
RightKun r;
return r;
};
std::cout << "[move(can not RVO)]" << std::endl;
RightKun r=createNoRVO();
}
std::cout << std::endl;
{
auto createCanNotMove=[](const RightKun &src, bool hoge)->RightKun
{
if(hoge){
return src;
}
return RightKun();
};
std::cout << "[copy(can not move)]" << std::endl;
RightKun r=createCanNotMove(RightKun(), true);
}
std::cout << std::endl;
{
auto rightValueArg=[](RightKun &&src, bool hoge)->RightKun
{
if(hoge){
return src;
}
return RightKun();
};
{
std::cout << "[right value arg]" << std::endl;
RightKun r=rightValueArg(RightKun(), true);
}
}
std::cout << std::endl;
{
auto moveExplicit=[](RightKun &&src, bool hoge)->RightKun
{
if(hoge){
// return std::move(src);
return static_cast<RightKun&&>(src);
}
return RightKun();
};
std::cout << "[right value cast]" << std::endl;
RightKun r=moveExplicit(RightKun(), true);
}
std::cout << std::endl;
{
auto moveFail=[]()->RightKun&&
{
return RightKun();
};
std::cout << "[fail !]" << std::endl;
RightKun r=moveFail();
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment