Consider this class:
class Foo
{
public:
~ Foo ()
{
std::cout << "~Foo\n";
}
typedef std::vector<std::string> Words;
const Words & words ()
{
return m_words;
}
private:
Words m_words = {"foo", "bar", "baz"};
};
Section 12.2 of the C++ standard specifies lifetimes of temporary objects. I thought this would be okay:
for (auto w : Foo () .words ())
std::cout << w << "\n";
But it wasn't
~Foo
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
[1] 10290 abort (core dumped) ./a.out
The standard is confusing me. Why is ~Foo
being called before the loop runs?
Aucun commentaire:
Enregistrer un commentaire