Returning a reference can work?

后端 未结 3 1642
天涯浪人
天涯浪人 2021-01-26 05:35

I used to think returning a reference is bad as our returned reference will refer to some garbage value. But this code works (matrix is a class):

co         


        
3条回答
  •  渐次进展
    2021-01-26 06:02

    This is safe up to a point, but very dangerous. The returned reference can't dangle, but if client code keeps it around, at some future point, the client is in for a big surprise, as his value suddenly changes to a new return value. And if you call get_matrix_temp more than max_matrix_temp times in a single expression, you're going to end up overwriting data as well.

    In the days before std::string, in code using printf, I used this technique for returning conversions of user defined types, where a "%s" specifier was used, and the argument was a call to a formatting function. Again, max_matrix_temp was the weak point: a single printf which formatted more instances of my type would output wrong data. It was a bad idea then, and it's a worse idea now.

提交回复
热议问题