问题描述
给定下面的代码。
我们假设这是一个 FP 检测并且我们可以安全地禁用警告是否正确?
我们假设这是一个误报,因为 std::to_string(int)
的结果将存在于堆栈中直到函数调用结束,但我们当然想确定......
// Definition of the function to be called
void my_function(const std::vector<std::string_view>& args) {}
// The function call complaining
my_function({
std::to_string(10) //error C26449: gsl::span or std::string_view created from a temporary will be invalid when the temporary is invalidated
});
// Of course we could write the code like this,but yeah we would like to know the theory and prefer the less bulk notation :)
auto var = std::to_string(10);
my_function({
var
});
这一切都归结为何时处理来自 std::string
的 std::to_string
。
解决方法
我们编写了一个小测试程序,它似乎按预期工作。我们只会禁用警告。
namespace std {
class test_string : public string
{
public:
test_string() : string() { std::cout << "test_string()"; }
~test_string() { std::cout << "~test_string()"; }
};
}
void test(const std::vector<std::string_view>& args)
{
std::cout << "test()";
}
int main(int argc,char* argv[])
{
std::cout << "begin_test";
test({
std::test_string()
});
std::cout << "end_test";
}