3 ms·
Actually having a constant reference as a member works as expected in C++ because the compiler will force you to initialize it a construction. It is true it wi
by shin_lao 11y ago
Actually having a constant reference as a member works as expected in C++ because the compiler will force you to initialize it a construction.
It is true it will not check at compilation that you access a const reference of a destroyed object, but to be honest with RAII this is not really a problem as the lifetime of your objects should be pretty clear, by construction.
In debug mode your program will quickly assert if you access a destroyed STL container.
To be honest I think in this case:
- either you want to snapshot the value and therefore you should clone the container (almost no performance cost for small containers)
- you want to access the current value but then it means you know about the lifetime.
- al2o3cr 11y ago"the lifetime of your objects should be pretty clear, by construction" Given the potentially-unbounded consequences of triggering UB in C++, "pretty clear" seems like not enough.