Re: [問題] operator overloading

看板C_and_CPP (C/C++)作者 (我要加入劍道社!)時間16年前 (2009/10/20 10:25), 編輯推噓3(3013)
留言16則, 4人參與, 最新討論串5/6 (看更多)
※ 引述《ACMTino (哈哈哈)》之銘言: : 標題: [問題] operator overloading : 時間: Tue Oct 20 01:55:03 2009 : : List Test::GetList() : { : return m_oList; : } : : Test oTest; : List oList = oTest.GetList(); 當你這樣寫的時候 [修正] - 實際上是呼叫一次 copy-assignment (oTest.GetList) - 以及一次 copy-constructor - 不過前面那個 copy-assignment 被 RVO 消掉了 - 所以沒呼叫到 List::operator= [/修正] 原本會呼叫兩次 copy-constructor 不過其中一次被 copy elision 的規則消除掉了 所以只呼叫一次 copy-constructor 而不會呼叫 List::operator= : 這樣子做還是會取得 m_oList, 等於 oList 是 m_oList 的別名 : 那修改 oList 就會改到 m_oList 不會 都 copy 兩次了當然不會是別名 (雖然實際上只 copy 一次) : : 請問要怎麼做才能避免修改到 m_oList, 或是能夠 overloading operator : 讓 GetList() 回傳 copy value 雖然你目前的 code 的確是取得 copy value 沒錯 但明顯是誤打誤撞的結果 因為 operator= 的內容就是錯的 如果是我會這樣寫... : class List : { : public: : List() {} : ~List() {} : // : Ele Get(int index) { return m_vEle[index]; } : // : bool Add(const char *sName) : { : Ele Ele; : strcpy(Ele.sName, sName); strncpy(Ele.sName, sName, MAX_NAME_LENGTH-1); : m_vEle.push_back(Ele); return true; : } : int GetSize() { return (int)m_vEle.size(); } : // : void Clear() { m_vEle.clear(); } : List operator=(const List &rhs) List& operator=(const List &rhs) : { : printf("....\n"); : if(this == &rhs) return *this; : this->Clear(); m_vEle = rhs.m_vEle; : return *this; : } : // : private: : vector<Ele> m_vEle; : }; : : : class Test : { : public: : // : Test() : { : m_oList.Add("XD"); : } : ~Test() {} : // : List GetList() List& GetList() : { : return m_oList; : } : : void Dump() : { : for(int i=0; i<m_oList.GetSize(); ++i) : { : printf("%s\n", m_oList.Get(i).sName); : } : } : : private: : List m_oList; : }; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.29.108

10/20 10:43, , 1F
inline function應該不會發生RVO..
10/20 10:43, 1F

10/20 10:43, , 2F
List oList = oTest.GetList(); 應該直接會變成
10/20 10:43, 2F

10/20 10:44, , 3F
List oList(oTest.m_oList);
10/20 10:44, 3F

10/20 10:45, , 4F
上面這行是pseudo code,直接寫這樣會因為private不給過
10/20 10:45, 4F

10/20 10:45, , 5F
但是Compiler的inline optimization應該是把code轉成類
10/20 10:45, 5F

10/20 10:45, , 6F
似這樣吧..
10/20 10:45, 6F

10/20 11:56, , 7F
inline 與否並不影響程式碼的語意
10/20 11:56, 7F

10/20 11:57, , 8F
若強制要求 compiler 不去 inline,上述程式碼結果不變
10/20 11:57, 8F

10/20 11:58, , 9F
因此 RVO 是比較 generalized 的解釋方法
10/20 11:58, 9F

10/20 12:08, , 10F
C++ 有修飾字可以叫她不要inline嘛!?
10/20 12:08, 10F

10/20 12:24, , 11F
gcc extension有noinline的能力 標準C++好像沒有
10/20 12:24, 11F

10/20 12:30, , 12F
gcc -fno-inline
10/20 12:30, 12F

10/20 13:02, , 13F
RVO是因為Compiler會把return value當成參數傳進function
10/20 13:02, 13F

10/20 13:03, , 14F
裡才會有的optimization吧..如果函式本身inline
10/20 13:03, 14F

10/20 13:03, , 15F
就不用把return value放在參數列上,自然也不會進行
10/20 13:03, 15F

10/20 13:03, , 16F
RVO啊..
10/20 13:03, 16F
※ 編輯: littleshan 來自: 140.112.29.108 (10/21 12:22)
文章代碼(AID): #1AtH-7go (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1AtH-7go (C_and_CPP)