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

mac2025-07-13  4

error: taking address of temporary [-fpermissive]

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

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

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

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

 

最新回复(0)