There’s probably a Google search that’ll answer this question but for the life of me, I can’t think of one that doesn’t get millions of unrelated answers.
So,
In MSVC text inside quotes “like this” is taken, I think, as a std::string or, maybe, std::string&. In g++/gcc it always seems to be taken as const char*. True?
I found a code snippet I wanted to play with and it contains
if(NULL == key)
throw exception("Empty key");
compiles just fine in MSVC/VC++(2008( but when I try it on g++ (4.4.3) I get
no matching functions for calls to std::exception::exception(const char&)
I got this to work:
if (NULL == key)
{
std::string estr ("Empty key");
throw exception("Empty key");
}
But that’s just plain ugly.
This got me different errors:
std::string estr ("");
if (NULL == key)
{
estr = "Empty key";
throw exception("Empty key");
}
I have no clue what exception() expects as its input. I did find something that suggested std::string or maybe std::string& but I lost that page and the millions of unhelpful pages I’ve found since are, well, useless. Have all kinds of info on exception class, exception use,….
Short of my ugly fix, is there a simple way to tell g++ that “this is a std::string” not a const char& and still keep VC++ happy? (obviously I’m trying to do cross compilable code from single source.)
And for that matter, how id
throw exception("Empty key");
different from
throw "Empty key";
Thanks,
Wes
A string literal always has the type of an array of
char, with a size just large enough to contain the characters in the literal with a null terminator. So"Empty key"has the typechar[10]. This can be implicitly converted to eitherchar const *orstd::stringif required.The error is because
exceptionis intended as a base class for exception types, not something you instantiate directly. You should throw one of the types defined in<stdexcept>such asstd::runtime_error(which can be constructed using a string), or define your own type that inheritsstd::exceptionand overrideswhat().I’m guessing that Microsoft has added a non-standard constructor to
std::exception. They like to extend the language in strange ways.