How come a non-const reference cannot bind to a temporary object?

前端 未结 11 1858
长情又很酷
长情又很酷 2020-11-21 05:19

Why is it not allowed to get non-const reference to a temporary object, which function getx() returns? Clearly, this is prohibited by C++ Standard but I am in

11条回答
  •  一个人的身影
    2020-11-21 05:26

    Seems like the original question as to why this is not allowed has been answered clearly: "because it is most likely an error".

    FWIW, I thought I'd show how to it could be done, even though I don't think it's a good technique.

    The reason I sometimes want to pass a temporary to a method taking a non-const reference is to intentionally throw away a value returned by-reference that the calling method doesn't care about. Something like this:

    // Assuming: void Person::GetNameAndAddr(std::string &name, std::string &addr);
    string name;
    person.GetNameAndAddr(name, string()); // don't care about addr
    

    As explained in previous answers, that doesn't compile. But this compiles and works correctly (with my compiler):

    person.GetNameAndAddr(name,
        const_cast(static_cast(string())));
    

    This just shows that you can use casting to lie to the compiler. Obviously, it would be much cleaner to declare and pass an unused automatic variable:

    string name;
    string unused;
    person.GetNameAndAddr(name, unused); // don't care about addr
    

    This technique does introduce an unneeded local variable into the method's scope. If for some reason you want to prevent it from being used later in the method, e.g., to avoid confusion or error, you can hide it in a local block:

    string name;
    {
        string unused;
        person.GetNameAndAddr(name, unused); // don't care about addr
    }
    

    -- Chris

提交回复
热议问题