在g ++中使用异常

Viv*_*mar 4 c++ exception-handling

在下面的代码中获取编译器错误,这些代码std::exception 在linux上引入了g ++ 4.8.2.任何有关此错误即将发生的建议将非常有帮助.

#include <iostream>
#include <stdexcept>

void function()
{
     std::exception e((char*)"mmmm");
     throw e;
}


int main(int argc, const char* arg[]) {

    try {
        function();
    }
    catch(const std::exception& e) {
        e.what();
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

$ g++ t.cpp
t.cpp: In function ‘void function()’:
t.cpp:6:33: error: no matching function for call to ‘std::exception::exception(char*)’
   std::exception e((char*)"mmmm");
                                 ^
t.cpp:6:33: note: candidates are:
In file included from /usr/include/c++/4.8/ios:39:0,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from t.cpp:1:
/usr/include/c++/4.8/exception:63:5: note: std::exception::exception()
     exception() _GLIBCXX_USE_NOEXCEPT { }
     ^
/usr/include/c++/4.8/exception:63:5: note:   candidate expects 0 arguments, 1 provided
/usr/include/c++/4.8/exception:60:9: note: std::exception::exception(const std::exception&)
   class exception
         ^
/usr/include/c++/4.8/exception:60:9: note:   no known conversion for argument 1 from ‘char*’ to ‘const std::exception&’
Run Code Online (Sandbox Code Playgroud)

编辑1

但是代码在Visual Studio 2010编译器中编译并运行良好.

_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception()
    : _Mywhat(NULL), _Mydofree(false) { }

_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception(const char * const & _What)
    : _Mywhat(NULL), _Mydofree(false)
    {
    _Copy_str(_What);
    }

_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception(const char * const & _What, int)
    : _Mywhat(_What), _Mydofree(false) { }

_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception(const exception& _That)
    : _Mywhat(NULL), _Mydofree(false)
Run Code Online (Sandbox Code Playgroud)

C++标准对此有何看法?

Aar*_*ham 7

std::exception没有带std :: string或char*的构造函数.也许你想用std::runtime_error


Ben*_*ley 1

no matching function for call to ...意味着您正在尝试调用一个不存在的函数。std::exception没有采用 achar*或任何可以从 a 转换的构造函数char*。它只有一个默认构造函数和一个复制构造函数。