C++ ASSERT\u THROW认为我的异常属于另一种类型

C++ ASSERT\u THROW认为我的异常属于另一种类型,c++,googletest,C++,Googletest,在Google测试中,当我运行以下测试时: void ThrowInvalidArgument() { throw new std::invalid_argument("I am thrown an invalid_argument"); } TEST(ExpectExceptions, Negative) { ASSERT_THROW(ThrowInvalidArgument(), std::invalid_argument); } 我得到以下失败: error: Expecte

在Google测试中,当我运行以下测试时:

void ThrowInvalidArgument()
{
   throw new std::invalid_argument("I am thrown an invalid_argument");
}

TEST(ExpectExceptions, Negative)
{
  ASSERT_THROW(ThrowInvalidArgument(), std::invalid_argument);
}
我得到以下失败:

error: Expected: ThrowInvalidArgument() throws an exception
                 of type std::invalid_argument.
       Actual: it throws a different type.
[  FAILED  ] ExpectExceptions.Negative (1 ms)

我做错了什么?

您正在抛出
std::invalid_参数*
类型的实例,即指针

而是抛出一个对象:

void ThrowInvalidArgument()
{
     throw std::invalid_argument("I am thrown an invalid_argument");
     //   ^ (no new)
}

扩展Pjotr的有效答案:异常总是应该从普通临时实例中抛出,并作为常量引用捕获:

void ThrowInvalidArgument() {
    throw std::invalid_argument("I am thrown an invalid_argument");
}

void Elsewhere {
    try {
    }
    catch(const std::invalid_argument& invalidArgEx) {
    }
}

... 除非您计划修改异常并重新引用它,否则在这种情况下,将执行un const引用。catch(MyExtand EX){Ex.AddioTeXeXiffic信息(…这个信息将有助于诊断问题…);抛出;} DaleWilson,我会考虑在第一的位置做如此糟糕的设计。虽然可能有一些有效的用例,但我在过去30年中没有遇到过一个。