temporary object, function parameters and implicit cast

前端 未结 3 1708
遇见更好的自我
遇见更好的自我 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
    

提交回复
热议问题