何时可以返回引用
EFfective C++和More Effective C++中有講解。
“條款23: 必須返回一個對象時不要試圖返回一個引用”
“條款31: 千萬不要返回局部對象的引用,也不要返回函數內部用new初始化的指針的引用”
?
為什么要返回引用呢——為了實現鏈式操作。
返回一個對象不行嗎?為什么有時要返回引用呢?主要是為了實現鏈式操作。
看一個例子就明白了:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | ? | MyString& MyString::operator =(const?MyString &other) { ??? /*if (this != &other) { ??????? size = strlen(other.data); ??????? char *temp = new char[size + 1]; ??????? strcpy(temp, other.data); ??????? delete []data; ??????? data = temp; ??? } ??? return *this;*/ ? ??? if (this != &other) { ??????? MyString strTmp(other); ? ??????? char *pTmp = strTmp.data; ??????? strTmp.data = data; ??????? data = pTmp; ??? } ? ??? return *this; } |
當返回引用時,我們可以實現鏈式操作如 (s1 = s2) = s3.如果返回的是對象,就不能這么操作了!
MyString s1;
MyString s2;
MyString s3 = “hello”;
(s1 = s2) = s3;
如果返回的是引用,則s1被賦值為"hello";如果是局部對象,則s1沒被賦值!
?
?
?
注意和+ – * /運算符重載相區別(返回局部對象):
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | ? | String String::operator +(const String &str)??? { ??? String newstring; ??? if (!str.m_string) ??? { ??????? newstring = *this; ??? } ??? else?if (!m_string) ??? { ??????? newstring = str; ??? } ??? else ??? { ??????? int len = strlen(m_string)+strlen(str.m_string); ??????? newstring.m_string = new?char[len+1]; ??????? strcpy(newstring.m_string,m_string); ??????? strcat(newstring.m_string,str.m_string); ??? } ??? return newstring; } |
何時返回引用呢
有兩種情況可以返回引用。一種是普通函數,返回傳入參數的引用;另一種是類方法函數,返回this對象的引用。
只要記住這兩種情況,其他情況如果可以也是沒什么意義的。
?
一、返回傳入參數的引用。
如運算符<<的友元重載形式:
| 1 2 3 4 5 | ? | ostream& operator<< (ostream &out, MyString &s) { ??? out << s.data; ??? return out; } |
?
二、返回this對象的引用。
即上面string的 = 運算符重載。
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | ? | MyString& MyString::operator =(const?MyString &other) { ??? /*if (this != &other) { ??????? size = strlen(other.data); ??????? char *temp = new char[size + 1]; ??????? strcpy(temp, other.data); ??????? delete []data; ??????? data = temp; ??? } ??? return *this;*/ ? ??? if (this != &other) { ??????? MyString strTmp(other); ? ??????? char *pTmp = strTmp.data; ??????? strTmp.data = data; ??????? data = pTmp; ??? } ? ??? return *this; } |
?
?
最終總結:返回引用的情況有兩種,一種是普通函數,返回傳入參數的引用;另一種是類方法函數,返回this對象的引用。
不可以返回局部對象的引用,也不要返回函數內部用new初始化的指針的引用(可能會造成內存泄露).
轉載于:https://www.cnblogs.com/helloweworld/p/3208585.html
總結
- 上一篇: 不错html5画布效果,可惜网站不需要。
- 下一篇: tomcat使用说明