关于函数不能返回局部对象的引用或者局部对象的指针
来源:互联网 发布:html5手机端模板 知乎 编辑:程序博客网 时间:2024/06/07 22:08
#include<iostream>#include<vector>#include<string>using namespace std;vector<int> globalObj_one;//全局变量1vector<int> *globalObj_two = new vector<int>();vector<int> fun1(){vector<int> funObj_one;vector<int> *funObj_two = new vector<int>();for(int i = 0;i<10;++i){funObj_one.push_back(i);funObj_two->push_back(i);}return funObj_one;//返回局部对象的拷贝}vector<int>& fun2()//返回局部对象的引用{vector<int> funObj_one;vector<int> *funObj_two = new vector<int>();for(int i = 0;i<10;++i){funObj_one.push_back(i);funObj_two->push_back(i);}return funObj_one;}vector<int>* fun3(){vector<int> funObj_one;vector<int> *funObj_two = new vector<int>();for(int i = 0;i<10;++i){funObj_one.push_back(i);funObj_two->push_back(i);}return funObj_two;//返回堆对象指针}vector<int>* fun4(){vector<int> funObj_one;vector<int> *funObj_two = NULL;for(int i = 0;i<10;++i){funObj_one.push_back(i);}funObj_two = &funObj_one;//指针指向一个局部对象return funObj_two;//返回局部对象指针}int main(){vector<int> mainObj_one;vector<int> mainObj_two;vector<int> *mainObj_three = NULL;vector<int> *mainObj_four = NULL;mainObj_one = fun1();//返回局部对象的拷贝(正常)for(auto iter = mainObj_one.begin();iter!=mainObj_one.end();++iter)cout<<*iter<<' ';cout<<endl;mainObj_three = fun3();//返回堆对象的指针(正常)for(auto iter = mainObj_three->begin();iter!=mainObj_three->end();++iter)cout<<*iter<<' ';cout<<endl;mainObj_two = fun2();//返回局部对象的引用(无法打印,对象已被析构)for(auto iter = mainObj_two.begin();iter!=mainObj_two.end();++iter)cout<<*iter<<' ';cout<<endl;mainObj_four = fun4();//返回局部对象的指针(无法打印,对象已被析构,指针指向不存在的对象,并且程序运行出错)for(auto iter = mainObj_four->begin();iter!=mainObj_four->end();++iter)cout<<*iter<<' ';cout<<endl;return 0;}
阅读全文
0 0
- 关于函数不能返回局部对象的引用或者局部对象的指针
- 不能返回局部对象的引用
- c++返回函数局部对象的引用
- c++返回函数局部对象的引用
- 返回局部对象的引用,返回函数内部用new初始化的指针的引用
- 返回局部对象的引用和返回局部对象的指针
- 不要返回局部对象的引用或指针
- 不要返回局部对象的引用
- 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用
- 不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用
- 为什么不能返回局部对象的应用
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- 关于C++函数返回局部对象的详细分析
- 返回指向局部变量指针的函数 与 返回局部变量引用的函数
- 条款31: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用 (转自effective c++ second edition)
- Effective C++ 条款31: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用
- 条款 31: 千万不要返回局部对象的引用,也不要返回函数内部用 new 初始化的 指针的引用
- 关于返回局部变量的指针或引用
- Android 仿iphone提醒事项(二)
- spring事务的七种传播属性和五种隔离级别
- python学习之集合
- hive的用户和用户权限
- 分布式事务最终一致性常用方案
- 关于函数不能返回局部对象的引用或者局部对象的指针
- RabbitMQ高可用性集群镜像实施方案
- python exercise1
- Facebook Surround360 学习笔记--(2)算法原理
- MongoDB总结(1)
- 关于自定义的时间类型,,,前后台展示的不同格式
- 让studio编译速度飞起来
- 交叉编译zlib
- 嵌入式操作系统uC/OS-II的定时器Timer使用及分析