Googletest does not accept temporary object in EXPECT_THROW

thumper picture thumper · Jun 23, 2011 · Viewed 12.2k times · Source

I have a class that has no default constructor, but the constructor may throw. I was wanting to have a test like:

EXPECT_THROW(MyClass(param), std::runtime_error);

But the compiler, g++, complains that there is no default constructor for MyClass. However, the following...

EXPECT_THROW(MyClass foo(param), std::runtime_error);

...works, and the test passes as expected. Why though won't Googletest accept the temporary object?

class MyClass
{
public:
  MyClass(std::string const& filename);
  //...
};

Interestingly enough, I had refactored my test to not have the filename in a separate variable, and when asked to check I found the following works:

EXPECT_THROW(MyClass("somefilename"), std::runtime_error);

However the following doesn't:

std::string filename("somefilename");
EXPECT_THROW(MyClass(filename), std::runtime_error);

Answer

Bulletmagnet picture Bulletmagnet · Nov 13, 2015

If you're hit with the "most vexing parse", the cure is often uniform initialization:

EXPECT_THROW(MyClass{param}, std::runtime_error);

(assuming your compiler understands C++11).