小编use*_*976的帖子

返回 std::tie - 悬空引用?

关于从函数返回 std::tie 的问题。如果我理解正确,那么 std::tie 仅包含引用。因此,返回指向函数局部变量的 std::tie 是一个非常糟糕的主意。编译器不应该能够检测到这一点并发出警告吗?

实际上,我们的代码中有这个错误,而我们的所有编译器和清理程序都没有检测到它。我很困惑任何工具都没有报告这一点。或者我理解有什么不正确的吗?

#include <tuple>

struct s_t {
    int a;
};

int& foo(s_t s) {
    return s.a; // warning: reference to local variable 's' returned
}

int& bar(s_t &s) {
    return s.a; // ok
}

auto bad(s_t s) {
    return std::tie(s.a); // no warning
}

auto fine(s_t &s) {
    return std::tie(s.a); // no warning
}

int main() {

    s_t s1,s2;

    auto bad_references = bad(s1);
    auto good_references = fine(s2);
    // ...

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ gcc-warning

8
推荐指数
1
解决办法
529
查看次数

标签 统计

c++ ×1

gcc-warning ×1