函数返回类对象的引用——不可以

关于函数返回值为类对象:

#include <iostream>
using namespace std;

class A 
{ 
	public: 
	A()
	{
	    cout<<this<<" constructor"<<endl; 
	}
	A(const A &other) 
	{
		cout<<this<<" cp contructor from "<<&other<<endl; 
	} 
	A & operator=(const A &other) 
	{
		cout<<this<<" operator = "<<&other<<endl; 
		return *this;
	}
	~A()
	{
		cout<<this<<" destructor"<<endl;
	}
};

A& foo()
{
	A a;
	return a;  //QT中会有warning提示:reference tpo stack memory associated with local variable 'a' returned.
}

int main()
{
	A a = foo();
	return 0;
}

运行结果(运行环境)

0x7ffc3896ad38 constructor
0x7ffc3896ad38 destructor
0x7ffc3896ad58 cp contructor from 0x7ffc3896ad38
0x7ffc3896ad58 destructor

Qt环境运行结果:

0x61fe6f constructor
0x61fe6f destructor
0x61fe9f cp contructor from 0
0x61fe9f destructor
可见,返回栈对象的引用是危险动作,建议不要这样做。

如果接收对象是引用类型,

int main()
{
	A& a = foo();
	return 0;
}

运行结果:

0x7ffc83c92038 constructor
0x7ffc83c92038 destructor

QT运行结果:

0x61fe9f constructor
0x61fe9f destructor
int main()
{
    foo();
    return 0;
}

QT运行结果同上。

拓展

const A& foo()
{
	return A(); //临时对象A()不能绑定非const的左值引用,即此时,返回引用类型时必须是const
}

int main()
{
	A a = foo();	
	return 0;
}

运行结果:

0x7ffe6056f918 constructor
0x7ffe6056f918 destructor
0x7ffe6056f938 cp contructor from 0x7ffe6056f918
0x7ffe6056f938 destructor

或者,

const A& foo()
{
	return A();
}

int main()
{
	const A& a = foo();	//必须是const,因为从const隐式转换为非const是不允许的
	return 0;
}

运行结果:

0x7ffe0e2459a8 constructor
0x7ffe0e2459a8 destructor
发布了15 篇原创文章 · 获赞 0 · 访问量 960

猜你喜欢

转载自blog.csdn.net/zimovv/article/details/98206921