The following code leads to this warning (vc and gcc -Wextra):
warning C4413: 'ReferencingContainer::_vector' : reference member is initialized to a temporary that doesn't persist after the constructor exits
But I don't understand why. I thought I was only passing through the reference.
#include <vector>
struct Referencing
{
Referencing(int const &x) : _x(x) {}
Referencing(int const &x, int dummy) : _x(x > 5 ? x : throw "error") {} // bad code, warning is ok
int const &_x;
};
struct Container
{
std::vector<double> _vector;
};
struct ReferencingContainer
{
ReferencingContainer(Container const &container)
: _container(container)
, _vector(container._vector.size() > 0 ? container._vector : throw "error") // <-- warning occurs here
{}
Container const &_container;
std::vector<double> const &_vector;
};
int main()
{
Referencing test1(21);
Referencing test2(22, 0);
Container container;
ReferencingContainer referencingContainer(container);
return 0;
}
Why is the compiler not happy with my code? Do I really have to worry that my object will reference a temporary?