Function returning a car with automatic parameter munmap_chunk (): invalid pointer

I am testing a new feature for GCC 4.9 (auto in parameter) and getting some weird error.

#include <iostream> #include <vector> auto foo(auto v) { for (auto&& i : v) std::cout << i; } int main() { foo(std::vector<int>{1, 2, 3}); } 

This gives me the following error:

 *** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x00007f87f58c6dc0 *** ======= Backtrace: ========= /lib/x86_64-linux-gnu/libc.so.6(+0x7e846)[0x7f87f4e4c846] ./a.out[0x400803] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7f87f4def76d] ./a.out[0x400881] 

Also, if I do return 0 , I get:

 main.cpp: In instantiation of 'auto foo(auto:1) [with auto:1 = std::vector<int>]': main.cpp:13:34: required from here main.cpp:8:12: error: could not convert '0' from 'int' to 'std::vector<int>' return 0; 

It seems strange that both auto are output the same. What can I do to fix it?


Please note that the following works just fine:

 auto foo(auto v) { return 'a'; } int main() { char c = foo(42); } 

My tests seem to indicate that pointers cause return type and v that should be output the same. For example int* and make_unique<int>(42) . However, the vector is the one that gives the error.

+4
source share
1 answer

I do not think that the parameter can be deduced in this way - sp2danny

I believe that using auto like this makes old auto sense
(AFAIK, in this case auto = int , and int cannot be converted to std::vector ).


He is currently working in lambdas

 [](const auto& v)->void{for(auto&&i:v) std::cout<<i;} 

But I believe that the best solution in this case is to create a template

 template<typename T> void foo(const T& t){ for (auto&& i : t) std::cout << i; } 
0
source

Source: https://habr.com/ru/post/982430/


All Articles