简体   繁体   English

C++ 异常字符串在带有 Xcode 和 CLion 的 Mac OS 上显示为垃圾

[英]C++ exception string displayed as garbage on Mac OS with Xcode and CLion

I'm learning C++.我正在学习 C++。 I tried the following code on my MBP, macOS 10.14.6, Xcode 11.0.我在我的 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;
}

Instead of getting string "Exception" in the terminal, text "0\365\277\357\376" was outputted.不是在终端中获取字符串“Exception”,而是输出文本“0\365\277\357\376”。

Compiled with CLion, the output is something like this: `'��� 使用 CLion 编译,output 是这样的:`'���

The code works fine on Windows 10, VS 2019.该代码在 Windows 10,VS 2019 上运行良好。

Your code has undefined behavior.您的代码具有未定义的行为。 This is a very subtle issue that really only applies to arrays.这是一个非常微妙的问题,实际上只适用于 arrays。 When you do当你这样做

char message[10] {"Exception"};

message is local to the function. message是 function 的本地消息。 When you throw it, instead of copying the array, what happens is the array decays into a pointer, and it is the pointer that gets copied.当你抛出它时,不是复制数组,而是数组衰减为一个指针,而被复制的是指针。 Because of this you are left with a pointer to message but message no longer exists after you exit the function.因此,您会留下一个指向message的指针,但在您退出 function 后message不再存在。

If you need to throw a c-string, then the correct method if如果你需要抛出一个 c 字符串,那么正确的方法是

throw "message to throw";

This works because "message to throw" is implcitly static and because of that it will live for the life of the program.这是有效的,因为"message to throw"是隐含的static并且因此它将在程序的生命周期中存在。 When you catch the pointer, the pointer still refers to a valid object unlike when you returned it from an array.当您捕获指针时,该指针仍然指向有效的 object,这与从数组中返回它时不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM