c++operator-overloadinggooglemock

How to use gmock MOCK_METHOD for overloaded object reference?


I have the object reference overloaded to return a value, for example:

class MyClass : public MyClassInterface {
  public:
    virtual ~MyClass() override;
    operator const int&() const override {
        return m_value;
    }
  private:
    int m_value{};
};

to get the value with:

MyClass myclass;
int val = myclass;

Now I would like to mock this operator method and found How to use gmock MOCK_METHOD for overloaded operators?. I verified the example as follows:

class Foo {
  public:
virtual ~Foo() {}
virtual int operator[](int index) = 0;
};

class MockFoo : public Foo {
  public:
MOCK_METHOD(int, BracketOp, (int index));
virtual int operator[](int index) override { return BracketOp(index); }
};

This compiles without error. Now I try to modify this example to fit to my needs:

class Bar {
  public:
virtual ~Bar() {}
virtual operator const int&() = 0;
};

class MockBar : public Bar {
  public:
MOCK_METHOD(int, RefOp, ());
virtual operator const int&() override { return RefOp(); }
};

But now I get a compiling error:

error: returning reference to temporary [-Werror=return-local-addr]
 1173 |     virtual operator const int&() override { return RefOp(); }
      |                                                     ~~~~~^~

What I'm doing wrong? How can I make class Bar compiling like class Foo?


Solution

  • To your original code:

    MOCK_METHOD(const int&, value, (), (const));
    

    To the updated code

    MOCK_METHOD(const int&, RefOp, ());