问题
I'm testing out new feature for GCC 4.9 (auto in parameter) and getting some weird bug.
#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 is giving 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;
Seems strange that both auto are deduced to be the same. What can I do to fix?
Note that the following works 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 to be deduced to same. For example int* and make_unique<int>(42). However, vector is the one to give error.
回答1:
I dont think parameter types can be deduced that way – sp2danny
I belive that using auto like this invokes old auto meaning
(AFAIK, in this case auto=int, and int can't be converted to std::vector).
At the moment it works in lambdas
[](const auto& v)->void{for(auto&&i:v) std::cout<<i;}
But I think the best solution in this case is to write a template
template<typename T>
void foo(const T& t){
for (auto&& i : t)
std::cout << i;
}
来源:https://stackoverflow.com/questions/26571592/function-returning-auto-with-auto-parameter-munmap-chunk-invalid-pointer