cg-tuwien / Auto-Vk

Afterburner for Vulkan development; Auto-Vk is a modern C++ low-level convenience and productivity layer atop Vulkan-Hpp.
MIT License
281 stars 18 forks source link

Uniformly return by value #29

Open johannesugb opened 4 years ago

johannesugb commented 4 years ago

As pointed out in some C++ talk that I'll have to find once again returning by reference or even const-reference can be very dangerous. Because if the returnee dies, the reference is dangling. Therefore, one should always return by value.

There are some exceptions to this rule where it is okay to return by reference --- namely when it can be ensured with certainty that the returnee outlives anything that could be done with a returned reference. Specifically, that applies to:

In many cases (e.g. returning a handle) return by value has probably exactly the same performance cost as returning the reference. I.e. in many cases, you don't get anything positive from returning a reference. In some cases, return by reference can be cheaper: e.g. when returning a vector of something. However, correctness is always more important than performance.

Actually, there is also a potential "security" risk: By const_cast-ing away the const of a const T&, one could modify the internal state through the returned reference.

Definition of Done: