8

I have testing code which does something like

EXPECT_CALL(mock, getSomeString()).WillOnce(Return(&testString));

where getSomeString() is returning by reference:

std:string& getSomeString();

and get

../../../../src/test/unit/gmock/gmock-actions.h: In member function ‘testing::internal::ReturnAction<R>::operator testing::Action<Func>() const [with F = const std::string&(), R = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]’:
../../../../src/test/unit/MyTests.cc:148:   instantiated from here
../../../../src/test/unit/gmock/gmock-actions.h:467: error: creating array with negative size (‘-0x00000000000000001’)

What is the cause?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Alexander Torstling
  • 18,552
  • 7
  • 62
  • 74

1 Answers1

25

Check gmock-actions.h:467 and you'll see:

GMOCK_COMPILE_ASSERT_(
        !internal::is_reference<Result>::value,
        use_ReturnRef_instead_of_Return_to_return_a_reference);

So the answer is to use ReturnRef instead of Return:

EXPECT_CALL(mock, getSomeString()).WillOnce(ReturnRef(testString));
Alexander Torstling
  • 18,552
  • 7
  • 62
  • 74
  • @feuGene. I agree that it's unhelpful, but I don't think it's googles fault. It's mostly a generally available way of generating a compile-time error: http://stackoverflow.com/questions/16192575/c-compile-time-assertions-can-we-throw-a-compilation-error-if-some-conditio – Alexander Torstling Mar 14 '17 at 11:00