我想寫一個類來處理異常。我認爲增加一個<運營商給我一個簡單的方法來拋出錯誤信息會很有用。貝婁是我迄今爲止解決這個問題的方法。有一件事情是讓我煩惱的是,如果我在析構函數中刪除流(如我的代碼所示),我會得到一個段錯誤。 Bellow是我的異常處理類的完整代碼。我不知道在析構函數達到它之前可能會刪除流。段錯誤刪除類成員指針流
class prc_exception : public std::exception {
private:
int line_num;
std::ostringstream* msg;
public:
prc_exception(const char* part, const int line) throw()
: exception() {
msg = new std::ostringstream();
*msg << "<parcer:" << part << ":" << line << ">: ";
}
~prc_exception() throw() { delete msg; }
virtual const char* what() const throw() { return msg->str().c_str(); }
virtual const int line() const throw() { return line_num; }
template <class T> prc_exception& operator<<(const T& rhs)
{ *msg << rhs; return (*this); }
};
此外,如果有人可以建議一個更好的方式來處理我想要做的事情,請給我一個建議。 我想有可用這樣一個東西:
throw prc_exception("code_part",__LINE__) << "More info";
,當抓到會有它就是()函數返回一個字符串,如:
<parcer:code_part:36>: More info
非常感謝。
已解決: 正如@polkadotcadaver建議的那樣,添加一個Copy構造函數和一個複製賦值操作符修復了這個問題。固定代碼發揮預期的作用: 的#include 的#include
using namespace std;
class prc_exception : public std::exception {
private:
int line_num;
std::ostringstream msg;
public:
prc_exception(const char* part, const int line) throw()
: exception() {
msg << "<parcer:" << part << ":" << line << ">: ";
}
/** Copy Constructor */
prc_exception (const prc_exception& other)
{
line_num = other.line();
msg << other.what();
}
/** Copy Assignment Operator */
prc_exception& operator= (const prc_exception& other)
{
line_num = other.line();
msg << other.what();
return *this;
}
~prc_exception() throw() { }
virtual const char* what() const throw() { return msg.str().c_str(); }
virtual const int line() const throw() { return line_num; }
template <class T> prc_exception& operator<<(const T& rhs)
{ msg << rhs; return (*this); }
};
int main()
{
try
{
throw prc_exception("hello", 5) << "text." << " more text.";
} catch (exception& e) {
cout << e.what() << endl;
}
return 0;
}
查一查怎麼寫拷貝賦值運算符在這樣的情況下,複製和交換成語(請注意,我還沒有嘗試過!) – polkadotcadaver