0

I am getting segmentation fault when I am returning l-value or r-value reference of object field from a function. Can anyone please explain me? I have included the code that I wrote.

int randomItem1(const vector<IntCell>& x) { // works fine
    return x[0].read();

The code above works fine. However, the following code gives me segmentation fault.

const int& randomItem2(const vector<IntCell>& x) { // segmentation fault
    return x[0].read();

int&& randomItem3(const vector<IntCell>& x) { // segmentation fault
    return x[0].read();

IntCell class definition:

class IntCell {
private:
    int storedValue;
public:
    IntCell(int val):storedVal{val} {}
    int read() const {
        return storedVal;
    }
};

Edit: I have included the class definition for IntCell.

0 Answers0