std::function 中不允许引用返回类型吗?



当我尝试设置绕过函数参数时,我发现给定的引用返回类型将带来SEGV,因为地址无效。我有一段玩具代码,你可以玩。当我用指针替换引用返回类型时,一切正常。

/* This doc is to investigate the issue brought by reference return type of a
* functor argument std::function. We expect it can pass the bypass function
* defined in top layer to less-context bottom layer and still work as designed.
* However we see weird behavior when it is std::function<const std::string&(int)>.
* Instead, std::function<const string*(int)> works fine...
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <functional>
using namespace std;
// This class stores vectror of numbers and divisors. API getRemainderRing picks
// those numbers' remainder equal to given number after division. Bypass function
// is passed in as argument to print the names.
class Elements {
public:
Elements() = default;
Elements(int32_t maxNum, int32_t divisor) : _div(divisor) {
_data.clear();
_data.reserve(maxNum);
for (int32_t i = 0; i < maxNum; i++) {
_data.push_back(i);
}
}
void getRemainderRing(int32_t rmd, const std::function<const string&(int32_t)>& getName, string* output) {
output->clear();
for (int32_t i : _data) {
if (i % _div == rmd) {
// crashes here. getName(i) pointing to address 0
*output += getName(i) + " ";
}
}
}
private:
vector<int32_t> _data;
int32_t _div;
};
int main () {
unordered_map<int32_t, string> numToStr;
numToStr[0] = "null";
numToStr[1] = "eins";
numToStr[2] = "zwei";
numToStr[3] = "drei";
numToStr[4] = "vier";
// The functor
std::function<const string&(int32_t)> getName = [&numToStr](int32_t i) { return numToStr[i]; };
Elements smallRing(4, 2); // contains {0,1,2,3}, divisor: 2
string result;
// This is actually to get all odd numbers < 4
smallRing.getRemainderRing(1, getName, &result);
// BOOM!
cout << result << endl;
return 0;
}

我希望输出是"eins drei "。我检查了 std::function 的文档 https://en.cppreference.com/w/cpp/utility/functional/function,没有提到返回类型 R 不能作为引用。我想知道这是否是规范中的已知缺陷/漏洞,或者我在使用它时犯了一些愚蠢的错误。

您的 lambda 没有指定返回类型,因此它被推断为按值返回string,而不是您想要的const string&引用。 如果您明确地返回 lambdaconst string&,SEGV 将不再发生:

[&numToStr](int32_t i) -> const string& { return numToStr[i]; }

现场演示

最新更新