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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With