Segfaults when declaring / defining a function that returns valarray with automatic type return

Can someone please help me understand why the following code is segfaults? The code works if I declare / specify mkto return std::valarray<int>. I think I'm not quite sure what I'm doing here auto.

#include <iostream>
#include <valarray>
auto mk(int x)
{
    return x * std::valarray<int>{1};
}
int main()
{
    auto v = mk(3);
    std::cout << v[0] << std::endl;
    return EXIT_SUCCESS;
}
+4
source share
1 answer

std::valarrayuses expression patterns. Template expressions do not work well with return type inference.

In this case, x*std::valarray<int>{1}it returns an expression that says "multiply xby some std::valarray<int>. By the time, when you use an object is mkboth xand std::valarray<int>fell outside the scope of.

( ): segfault. undefined.

, , . , auto.

- operator auto - , , - . , , " a valarray" - . .

+6

All Articles