cpp_weekly
cpp_weekly copied to clipboard
Reference Qualifiers for Class Member Functions
Channel
This is a "C++Weekly" episode request
Topics
What's wrong with the following code?
class Keeper
{
std::vector<int> m_Data {1,2,3};
public:
auto& items() { return m_Data; }
};
Keeper GetKeeper()
{
return {};
}
void UseKeeper()
{
for (auto& item : GetKeeper().items())
{
std::cout << item << "\n";
}
}
Keeper contains a vector of ints, which we construct in GetKeeper and use in UseKeeper. However, items() it returns a reference to the items, not the items themselves. So, when we call GetKeeper().items(), we then delete the underlying Keeper and it's items are left as a dangling reference. BAD!!!
To solve this, we can use reference qualifiers on items().
class Keeper
{
std::vector<int> m_Data {1,2,3};
public:
auto& items() & { return m_Data; }
auto items() && { return m_Data; }
};
Now; auto& items() & is called on l-value Keepers, returning a reference to the underlying data; and auto items() && is called on r-value Keepers, returning (moving) the underlying data itself.
Length
I imagine this episode shouldn't take more than 10 minutes.
The blogs below do nice write-ups of this issue, which I've copied my above example from.
https://andreasfertig.blog/2022/07/the-power-of-ref-qualifiers/ https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/