关于函数不能返回局部对象的引用或者局部对象的指针
2017-07-06 17:23
393 查看
#include<iostream> #include<vector> #include<string> using namespace std; vector<int> globalObj_one;//全局变量1 vector<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; }
相关文章推荐
- 函数 千万不要返回“局部对象”的引用或者指针
- 条款31: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用 (转自effective c++ second edition)
- 条款31: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Effective C++ 条款31: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用
- 不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- 条款 31: 千万不要返回局部对象的引用,也不要返回函数内部用 new 初始化的 指针的引用
- effective C++笔记之条款31、32: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针所指对象的引用、尽可能地推迟变量的定义
- 函数可以返回左值,不能返回局部对象的引用
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- 函数不能返回局部指针变量
- 为什么C++中千万不要返回局部对象或变量的引用和指针
- 不能返回局部对象的引用
- c++返回函数局部对象的引用
- Effective C++ 第二版 31)局部对象引用和函数内new的指针 32)推迟变量定义