Can someone suggest a good way or best practices to avoid such code errors?
When your class stores a const link to another object, you, as a programmer, take the responsibility of making sure that you do not keep the link to hang out.
Unless you have a good reason to store a const link, I would recommend keeping the value.
struct Foo { explicit Foo(const int& i) : i{i} {} void foo() const { std::cout << i; } int i; };
R sahu
source share