[英]C++ exception string displayed as garbage on Mac OS with Xcode and CLion
我正在學習 C++。 我在我的 MBP、macOS 10.14.6、Xcode 11.0 上嘗試了以下代碼。
include <iostream>
using std::cout;
using std::endl;
using std::cerr;
void errthrow();
int main(int argc, const char * argv[]) {
try {
errthrow();
} catch (const char* pEx) {
cerr << pEx << endl;
}
}
void errthrow()
{
char message[10] {"Exception"};
throw message;
}
不是在終端中獲取字符串“Exception”,而是輸出文本“0\365\277\357\376”。
使用 CLion 編譯,output 是這樣的:`'���
該代碼在 Windows 10,VS 2019 上運行良好。
您的代碼具有未定義的行為。 這是一個非常微妙的問題,實際上只適用於 arrays。 當你這樣做
char message[10] {"Exception"};
message
是 function 的本地消息。 當你拋出它時,不是復制數組,而是數組衰減為一個指針,而被復制的是指針。 因此,您會留下一個指向message
的指針,但在您退出 function 后message
不再存在。
如果你需要拋出一個 c 字符串,那么正確的方法是
throw "message to throw";
這是有效的,因為"message to throw"
是隱含的static
並且因此它將在程序的生命周期中存在。 當您捕獲指針時,該指針仍然指向有效的 object,這與從數組中返回它時不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.