函数返回自动带有自动参数munmap_chunk():无效指针 [英] Function returning auto with auto parameter munmap_chunk(): invalid pointer

查看:620
本文介绍了函数返回自动带有自动参数munmap_chunk():无效指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试新功能(对于GCC 4.9)(自动参数)并获取一些奇怪的错误。

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});
}

这给我以下错误:

*** 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]

此外,如果我返回0 ,我得到:

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;

看起来很奇怪,两个auto都被推断为相同。我可以做什么来解决?

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);
}



我的测试似乎表明指针导致返回类型和v被推导相同。例如 int * make_unique< int>(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.

推荐答案


我不认为参数类型可以推论出来 - sp2danny

I dont think parameter types can be deduced that way – sp2danny

我相信使用 auto 像这样会调用旧的 auto 含义

(AFAIK,在本例中为 auto = int int 不能转换为 std :: vector )。

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).

此时它在lambdas中工作

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;
}

这篇关于函数返回自动带有自动参数munmap_chunk():无效指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆