Custom string class (C++)

前端 未结 4 1684
灰色年华
灰色年华 2021-01-05 18:23

I\'m trying to write my own C++ String class for educational and need purposes.
The first thing is that I don\'t know that much about operators and that\'s why I want to

4条回答
  •  星月不相逢
    2021-01-05 18:32

    Here's what's going on:

    1. The constructor is indeed called twice. Once for "hello" and once for " world". The order is undefined.
    2. The CString::operator + is called on the 1st CString ("hello"), passing the second CString (" world") as it's argument. The return value of CString::operator + is a new CString
    3. Since you're assigning in initialization, i.e: CString a = [CString result of operator +], c++ will just call you're copy constructor. Hence the call to CString(CString& ) that you're seeing in the debugger.

    Now, that's 4 total objects just created, one for each string literal ("hello", and " world"), one for the concatenation of those (the result of the CString::operator + call, and one to hold the result (CString a = ...). Each one of those temporary objects will have it's destructor called.

    As for why you're not getting the printf, I have no idea. I just copy pasted your code in this file:

    #include 
    #include 
    
    [your code]
    
    int main(int argc,char* argv[]) {
      CString a = CString("hello") + CString(" world");
      printf(a);
    }
    

    And when I ran the resulting executable, I got hello world as the output. This is on Ubuntu with g++ 4.4. Not exactly sure why under the VS debugger it's not printing anything.

提交回复
热议问题