读书人

引用与指针的有关问题重新发一下

发布时间: 2013-11-15 22:28:15 作者: rapoo

引用与指针的问题,重新发一下
本以为自己对引用和指针的理解比较深刻,但是还是出现点问题,先贴出代码


#include <iostream>
using namespace std;
class A
{
publlic:
A(int i){x=i;}
~A(){"exit\n"}
int get(){return x;}
private:
int x;
};

A fun();
int main() {
A *r = &fun();
cout<<r->get()<<endl;
}
A fun()
{
A a(23);
return a;
}

这里 析构函数掉了两次,一次是 fun函数返回的时候,释放了a,还有一次是reurn 执行的时候,系统赋值了副本a,然后有把这个副本给释放了,导致了 r->get()的值为0,这是为何? 既然return的时候已经创建了一个副本,为什么又把它释放掉了呢???
但是如果我用引用接的话就是正常的,请看代码
本以为自己对引用和指针的理解比较深刻,但是还是出现点问题,先贴出代码

#include <iostream>
using namespace std;
class A
{
publlic:
A(int i){x=i;}
~A(){"exit\n"}
int get(){return x;}
private:
int x;
};

A fun();
int main() {
A &r = fun();
cout<<r.get()<<endl;
}
A fun()
{
A a(23);
return a;
}

c++指针引用,c++函数返回类
[解决办法]
引用:
Quote: 引用:

我觉得你根本没编译过你的代码!!!

~A(){"exit\n"}

你这是几个意思?

我修改了一下,这相当于你的代码了吧?
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;

class A
{
public:
A(int i)
{
x=i;
printf("[%p]A():[%d]\n",this,x);
}
~A()
{
printf("[%p]~A():[%d]exit\n",this,x);
}
int get()
{
return x;
}
private:
int x;
};

A fun();

int main()
{
A &r = fun();
cout<<"["<<r.get()<<"]"<<endl;
system("pause");
return 0 ;
}

A fun()
{
A a(23); //a是一个局部变量,它的声明周期只存在到fun()函数结束
return a; //值传递,将a的值返回之后,这里会第一次调用析构函数释放局部变量。
}



看编译结果:

server197/home/smsprev4/tmp/msq>g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:33: error: invalid initialization of non-const reference of type 'A&' from a temporary of type 'A'
被你说中了。。我现在手头上没有编译环境,我是昨天晚上发现的问题。。 那句话改成cout<<"exit\n";就可以了,我抄错了。

func() 函数的返回值是值传递的方式,a是一个局部变量,它的声明周期只存在到fun()函数结束,将a的值返回之后,这里会第一次调用析构函数释放局部变量。赋值语句执行完后 临时变量 所在空间已成为无效空间,再使用引用的 r 就是一个指向不特定内存的变量,作用相当于野指针了。
我刚试验了,在VC下这套代码是可以通过,但是在G++下,甚至编译时通不过的:
A &r = fun(); error: invalid initialization of non-const reference of type 'A&' from a temporary of type 'A'
从一个临时变量给一个引用初始化是不被允许的

读书人网 >C++

热点推荐