Turn a string into another string

I currently have this code to add a β€œtag” to the exception message, which gives me a very light version of the stack trace:

try {
    doSomething();
} catch (std::exception& e) {
    int size = 8 + _tcslen(e.what());
    TCHAR* error = new TCHAR[size];
    _sntprintf(error, size, TEXT("myTag: %s"), e.what());
    std::exception x = std::exception(error);
    delete []error;
    throw x;
}

It looks awful, and I'm sure you need to be in a simple way. Could you help me with this?

+3
source share
4 answers

how about this:

throw std::exception(std::string("myTag: ").append(e.what()).c_str());

The c_str () call was added and tested in Visual Studio, and it works (note: this does not compile in gcc, there is only a default constructor in the implementation).

+3
source

Why aren't you using std :: string?

try {
    doSomething();
} catch (const std::exception& e)
{
    throw std::exception(std::string("myTag: ") + e.what());
}

Other notes: As far as I know, std :: exception does not have such a constructor form (only its subclasses).

, TCHAR. std::exception::what - -, char*? , , std::basic_string<TCHAR>.

: a const char* ( - ). , , 10 13 :

throw some_exception(e.what() + '\n' + moreinfo);
+3

Yes there is.

std::string S1="Hello",S2=" World";
S1+=S2;
0
source

Why do not you use directly std::string. You can do it std::string s = std::string("myTag") + e.what(). And if you want the char * pointer to use c_str()a member function of the string.

0
source

Source: https://habr.com/ru/post/1719813/


All Articles