eranpeer / FakeIt

C++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
MIT License
1.22k stars 169 forks source link

Do/AlwaysDo returning int to const int& method will cause SIGSEGV #209

Closed oriolarcas closed 3 years ago

oriolarcas commented 4 years ago

If a method returns by constant reference, a Do/AlwaysDo lambda that returns by value will compile without warnings or errors:

struct Test {
    virtual const int& test_method() = 0;
    virtual ~Test() = default;
};

TEST_CASE("test case", "[test]") {
    Mock<Test> test_mock;
    int var = 42;
    When(Method(test_mock, test_method)).AlwaysDo([&var]() -> int {
        return var;
    });
    REQUIRE(var == test_mock.get().test_method());
}

See that the lambda returns int, while the method returns const int&. This causes segmentation fault.

This only happens if the method has const. In this example, a method returning int& won't compile as expected.

rpadrela commented 3 years ago

Change test_method() to return an int instead of const int&?

FranckRJ commented 3 years ago

You shouldn't read from a reference that point to a object that has been destroyed.