Observing weird behavior with 'auto' and std::minmax

喜欢而已 提交于 2019-11-29 09:48:46

This is one of those cases of where not to use auto as the type specifier. std::minmax returns a pair of references:

template< class T > 
std::pair<const T&,const T&> minmax( const T& a, const T& b );

That's what auto will deduce. But delta() returns a temporary. So when you write:

auto dim = std::minmax(gtl::delta(y, gtl::HORIZONTAL),
                       gtl::delta(y, gtl::VERTICAL));

dim is holding two dangling references. But when you write:

std::pair<int, int> dim1 = std::minmax(...);

You're just holding the values directly. That's why this works but auto doesn't. The extra conversion you're performing prevents you from holding dangling references.


Alternatively, and for completeness, you could use a different overload of minmax that doesn't return references:

template< class T >
std::pair<T,T> minmax( std::initializer_list<T> ilist);

which just involves some extra braces:

auto dim2 = std::minmax({gtl::delta(y, gtl::HORIZONTAL),
                         gtl::delta(y, gtl::VERTICAL)});

But I'd suggest just explicitly naming the type. That seems less error-prone to me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!