C++对象构建与使用,error: taking address of temporary [-fpermissive]

error: taking address of temporary [-fpermissive]

获取临时对象的地址,编译器是不允许的.
这里要理解什么是临时对象,
临时对象就是无名对象,在语句行上直接用类生成一个对象,
它的生命周期是在该行创建,又在该行销毁.
对于一个已经销毁或行将销毁的对象,你拿到它的地址是没有意义的,所以编译器这个婆婆就武断的告诉你,别拿这个地址,你拿它没有用,不许拿,它是临时对象地址.

临时对象在该行还是有意义的,例如qt就用qDebug()临时对象向屏幕输出打印信息.

下面给个简单的例子来理解对象的构建释放过程及临时对象的构建释放过程

#include 
// 用this 指针,可以区分到底哪一个对象被构建和销毁
struct A {
	int v;
	A(int x) 
	{
		v=x;
		printf("int construct! v:%d,this:%p\n",v,this);
	}
	A()
	{
		v=0;
		printf("default construct! v:0,this:%p\n",this);
	}
	A(const A& a)
	{
		v=a.v;
		printf("copyed construct v:%d,this:%p\n",v,this);
	}
	A& operator=(const A& a)
	{
		v=a.v;
		printf("assigned construct v:%d,this:%p\n",v,this);
		return *this;
	}
	~A()
	{
		printf("destructed! this:%p\n",this);
	}
};
 
/* 研究对象创建方式, 尤其是临时对象的生命周期
 * 打开,关闭相关的注释,编译运行可以了解其工作实质
 */
int main()
{
//	A(1);		//临时对象, 在该行创建,在该行又销毁
//	A a1 = A(1);	//临时对象被优化掉,仅进行一次整数构造
	printf("1---------\n");
	A a1;		//默认构造;
	printf("2---------\n");
	a1 = A(2);	// 赋值构造,临时对象被创建,在该行又被销毁
	printf("3---------\n");
	A a2(3);	//整数构造
	printf("4---------\n");
	a1=a2;		//赋值构造
//	void *p = & A(2);	//产生错误  error: taking address of temporary [-fpermissive]
	printf("haha\n");
//	printf("what's this %p\n",&a1);
	return 0;
}

附测试结果:
hjj@hjj-u7090:~/test/test_c++$ ./test_c++
1---------
default construct! v:0,this:0x7ffd1826f020
2---------
int construct! v:2,this:0x7ffd1826f024
assigned construct v:2,this:0x7ffd1826f020
destructed! this:0x7ffd1826f024
3---------
int construct! v:3,this:0x7ffd1826f024
4---------
assigned construct v:3,this:0x7ffd1826f020
haha
destructed! this:0x7ffd1826f024
destructed! this:0x7ffd1826f020
 

你可能感兴趣的:(#,c++,编程,c++,开发语言)