vendredi 30 août 2019

Is reference return type not allowed in std::function?

When I was trying to setup a bypass function argument, I found that given reference return type will bring SEGV because of invalid address. I have a piece of toy code you can play with. When I replace the reference return type by pointer, everything works fine.

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

I expect the output to be "eins drei ". I checked the doc of std::function https://en.cppreference.com/w/cpp/utility/functional/function, nowhere mentioned that return type R cannot be a reference. I am wondering if this is a known defect/hole in specification, or I made some silly mistakes on using it.

Aucun commentaire:

Enregistrer un commentaire