temporary object, function parameters and implicit cast

前端 未结 3 1709
遇见更好的自我
遇见更好的自我 2021-02-11 05:20

In the following scenario:

struct Foo
{
   // ...
   operator Bar() {... }  // implicit cast to Bar
}

Foo GetFoo() { ... }
void CallMeBar(Bar x) { ... }

// ...         


        
相关标签:
3条回答
  • 2021-02-11 05:38

    It will survive, but relying in that fact may be confusing, and may cause clients of your code to reach for the C++ Standard, ask questions on Stack Overflow, etc ;-). For instance what happens when someone does:

    Bar b = GetFoo();
    CallMeBar(b);
    

    This time, the Foo has gone before CallMeBar is called, but most programmers would want conversions to create an independent object, and hence for the code to behave the same as:

    CallMeBar(GetFoo());
    

    This is why std::string does not have an implicit cast to char*, unlike CString's cast to LPCTSTR. Instead, std::string has the c_str() member function, which has the same constraint but makes it a bit more obvious in calling code that it's not a real conversion:

    CallMePtr(GetString().c_str());   // OK
    
    char* p = GetString().c_str();    // Bad
    CallMePtr(p);                     // Badness manifests
    
    const string &s = GetString();    // use "the most important const"
    CallMePtr(s.c_str());             // Best be on the safe side
    
    0 讨论(0)
  • 2021-02-11 05:39

    Regardless of the cast, the temporary object(s) will "survive" the call to CallMe() function because of the C++ standard:

    12.2.3 [...] Temporary objects are destroyed as the last step in evaluating the fullexpression (1.9) that (lexically) contains the point where they were created. [...]

    1.9.12 A fullexpression is an expression that is not a subexpression of another expression.

    0 讨论(0)
  • 2021-02-11 05:44

    As long as you return them by value, they survive until CallMeBar is finished.

    Your cast operator is a little off, though. Should be:

    struct Foo
    {
       // ...
      operator Bar() {... }  // implicit cast to Bar
    }
    

    See e.g. http://msdn.microsoft.com/en-us/library/ts48df3y(VS.80).aspx

    0 讨论(0)
提交回复
热议问题