string& foo() { string* str = new string("abc"); return *str; } |
struct a_s { int a; }; a_s* foo() { struct a_s* sp = new struct a_s; return sp; } |
string & shorterString(string &s1,string &s2) { return s1.size()<s2.size()? s1:s2; //返回 //的是s1,或者s2.是你传递引用类型形参. //看了下面的两个函数你会发现,传递的形参里 //至少有一个是引用. .是用来被返回的. } |
const string &manip(const string&s) { string ret=s; return ret;// 错误,ret为局部对象. } |
char &get_val(string &str,int ix) { return str[ix]; } int main() { string s("a value"); cout<<s<<endl; get_val(s,0)='A'; // 这里可以用来赋值的, cout<<s<<endl; return 0; } |
#include <iostream> #include <string> using namespace std; string& foo() { string* str = new string("abc"); return *str; } int main() { string& a=foo(); cout<<a; } |
#include <iostream> #include <string> using namespace std; string& foo() { string* str = new string("abc"); cout << "Address in foo:" << str << endl; return *str; } int main(int argc,char *argv[]) { for(int i = 0; i < 10; ++i) { string *str1 = &foo(); cout << *str1 << endl; cout << "Address in main:" << str1 << endl; //delete str1; } return 0; } |
原帖由 garymb 于 2009-10-16 11:09 发表
你要搞清楚的是返回对象的引用和直接返回对象的区别,返回引用意味着你是直接返回对象本身,而直接返回对象是复制对象,那么你的第一个代码
string& foo()
{
string* str = new string("abc");
ret ...
欢迎光临 Chinaunix (http://bbs.chinaunix.net/) | Powered by Discuz! X3.2 |