1.如果返回值被用在赋给其它对象或作为其它函数的参数时,函数内部在已经创建有对象情况下,返回时时不在创建零时对象的,如果函数内的对象没有创建,只在返回时出现过,那么会在返回时创建,这个就是因为必须得有实例对象才能传值。
#include<iostream>
#include<string>
using namespace std;
string GetMyString()
{
return "This is a string";
}
class zheng
{
private:
int a;
public:
zheng() { a = 0;
cout << "Mvalue copy construct" << endl; };
zheng(zheng& z){
cout << "Lvalue copy construct" << endl;
}
zheng(zheng && z){
cout << "Rvalue copy construct" << endl;
}
zheng(const int&& x):a(x){
cout << "value copy construct" << endl;
}
~zheng(){
cout << "destruct construct" << endl;
}
void set(int b)
{
a = b;
}
};
struct test
{
private:
zheng a;
public:
test( zheng& s)
{
cout << "L zheng construct" << endl;
}
test( zheng&& s)
{
cout << "R zheng construct" << endl;
}
~test(){
cout << " zheng destruct" << endl;
}
};
zheng GetMyvalue()
{
zheng x1; //这里创建了返回是就不会创建了,如果直接在返回的地方写zheng,则会在返回的地方创建一个零时对象
// cout << " construct" << endl;
//x1.set(7);
//zheng x2(x1);
return x1;
}
int main(int argc, char const *argv[])
{
// {
// const string &s = GetMyString();
// }
// string a = "1234";
{
// GetMyvalue();
//zheng s(GetMyvalue());
//zheng y = s;
test s{GetMyvalue()};
// zheng s;
// zheng *p = &s;
// zheng &x1 = s;
}
return 0;
}