The following short program
#include <vector>
#include <iostream>
std::vector<int> someNums()
{
return {3, 5, 7, 11};
}
class Woop
{
public:
Woop(const std::vector<int>& nums) : numbers(nums) {}
void report()
{
for (int i : numbers)
std::cout << i << ' ';
std::cout << '\n';
}
private:
const std::vector<int>& numbers;
};
int main()
{
Woop woop(someNums());
woop.report();
}
has a dangling reference problem, that no compiler seems to warn about. The issue is that temporaries can be bound to const-refs, which you may then keep around. The question then is; Is there a method of avoiding getting into this problem? Preferably one that does not involve sacrificing const correctness, or always making copies of big objects.
In situation when some method keeps a reference after returning it is a good idea to utilize
std::reference_wrapperinstead of normal reference:Woop (std::vector<int> const &&) = delete;for your method: