Question

Let's assume that we need some class for wrapping std::string, and besides all other details, it provides an automatic conversion back to std::string, using a type cast operator:

class MyWrappedString {
    std::string m_value;
    /* ... */
public:
    inline operator std::string() const {
        return m_value;
    }
};

So, the operator will return a copy of the wrapped string object.

But, why is the following code seemingly correct?

MyWrappedString x;
const std::string& y = x;
// now, y should be a reference to a temporary, right?
std::cout << "y is: " << y << std::endl;

The conversion operator will return a temporary copy of m_value, so const std::string& y = x will create a reference to that temporary copy.

Why does this work? I remember there was some kind of extension of lifetime of referenced objects, but I am not sure.

And second question: is it possible to have a type cast operator that returns a const reference?

E.g.:

inline operator const std::string &() const {
    return m_value;
}

So, that the above code does not have to work on a temporary copy?

PS: This question is a bit related to: Lifetime of temporaries, but still a different issue.

Was it helpful?

Solution

const references are keeping the reference alive (even if it would have gone out out of scope normally) until the const reference goes out of scope

For the second question: yes, you can return a const reference, and the return value from the function will have to be assinged to a const reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top