#include <cstdio> // for printf, getchar.
using namespace std;
int g_count;
struct my_string
{
int id;
my_string()
{
this->id = ++g_count;
printf("my_string() / [id=%d]を生成\n", this->id);
}
~my_string()
{
if ( this->id > 0 )
printf("~my_string() / [id=%d]を破棄\n", this->id);
else
printf("~my_string() / 解放リソース無し\n");
}
my_string(my_string const &other)
{
this->id = ++g_count;
printf("my_string(my_string const &) / 生成[%d ← %d]\n",
this->id, other.id);
}
my_string(my_string &&other)
{
this->id = other.id;
other.id = -1;
printf("my_string(my_string &&) / [id=%d]を引き継ぎ\n", this->id);
}
void operator=(my_string const &other)
{
printf("operator=(my_string const &) / [id=%d]を破棄\n", this->id);
this->id = ++g_count;
printf("operator=(my_string const &) / 生成[%d ← %d]\n",
this->id, other.id);
}
void operator=(my_string &&other)
{
printf("operator=(my_string &&) / [id=%d]を破棄\n", this->id);
this->id = other.id;
other.id = -1;
printf("operator=(my_string &&) / [%d]を引き継ぎ\n", this->id);
}
};
my_string f()
{
return my_string();
}
void f2(my_string &r)
{
r = my_string();
}
int main()
{
my_string i;
printf("\n----f\n");
i = f(), printf(" (after return)\n");
printf("\n----f2\n");
f2(i), printf(" (after return)\n");
printf("\n----\n");
}
I2luY2x1ZGUgPGNzdGRpbz4gICAgCS8vIGZvciBwcmludGYsIGdldGNoYXIuCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgZ19jb3VudDsKCnN0cnVjdCBteV9zdHJpbmcKewoJaW50IGlkOwoKCW15X3N0cmluZygpCgl7CgkJdGhpcy0+aWQgPSArK2dfY291bnQ7CgkJcHJpbnRmKCJteV9zdHJpbmcoKSAvIFtpZD0lZF3jgpLnlJ/miJBcbiIsIHRoaXMtPmlkKTsKCX0KCgl+bXlfc3RyaW5nKCkKCXsKCQlpZiAoIHRoaXMtPmlkID4gMCApCgkJCXByaW50Zigifm15X3N0cmluZygpIC8gW2lkPSVkXeOCkuegtOajhFxuIiwgdGhpcy0+aWQpOwoJCWVsc2UKCQkJcHJpbnRmKCJ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