const char* 与 char* (C++)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6208565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:41:19  来源:igfitidea点击:

const char* vs char* (C++)

c++

提问by CppLearner

For the following program:

对于以下程序:

int DivZero(int, int, int);

int main()
{
    try {
        cout << DivZero(1,0,2) << endl;
    }
    catch(char* e)
    {
        cout << "Exception is thrown!" << endl;
        cout << e << endl;
        return 1;
    }
    return 0;
}

int DivZero(int a, int b, int c)
{
    if( a <= 0 || b <= 0 || c <= 0)
        throw "All parameters must be greater than 0.";
    return b/c + a;
}

Using char* e will give

使用 char* e 会给

terminate called after throwing an instance of 'char const*'

抛出“char const*”的实例后调用终止

According to C++ Exception Handling, the solution is to use const char*instead.

根据C++ Exception Handling,解决方案是使用const char*代替。

Further reading from function (const char *) vs. function (char *)said that

进一步阅读function (const char *) vs. function (char *)

The type of "String" is char*', not const char*'

(this is a C discussion I think...)

“字符串”的类型是char*', not const char*'

(这是我认为的 C 讨论...)

Additional reading on Stack Overflow char* vs const char* as a parametertells me the difference. But none of them address my questions:

额外阅读 Stack Overflow char* 与 const char* 作为参数告诉我区别。但他们都没有解决我的问题:

  1. It seems like both char*and string*have limit on the numbers of characters. Am I correct?
  2. How does adding the keyword constto char*eliminates that limit? I thought the only purpose of constis to set a flag that said "unmodifiable". I understand that const char*e means " the pointer which points to unmodifiable char type".
  1. 似乎char*string*都对字符数有限制。我对么?
  2. 将关键字const添加到char* 如何消除该限制?我认为const的唯一目的是设置一个表示“不可修改”的标志。我知道const char*e 的意思是“指向不可修改的 char 类型的指针”。

The solution to that error is to use constchar* e.

该错误的解决方案是使用constchar* e

Even const string* e doesn't work. (just for the sake of testing...)

甚至 const string* e 也不起作用。(只是为了测试......)

Can anyone explain, please? Thank you!

谁能解释一下好吗?谢谢!

By the way, I am on Ubuntu, compiled by GCC, on Eclipse.

顺便说一下,我在 Ubuntu 上,由 GCC 编译,在 Eclipse 上。

回答by David Given

The email you linked to about "String" is wrong (and confusing).

您链接到的关于“String”的电子邮件是错误的(并且令人困惑)。

Basically:

基本上:

char*is a pointer to an unbounded array of characters. Traditionally we consider such an array to be a C-string if it contains a set of valid characters followed by a \0. There's no limit to the size of the array.

char*是一个指向无界字符数组的指针。传统上我们认为这样的数组是一个 C 字符串,如果它包含一组有效字符,后跟一个\0。数组的大小没有限制。

const char*is a pointer to an unbounded array of immutablecharacters.

const char*是一个指向不可变字符的无限数组的指针。

string*is a pointer to a std::stringobject, and is entirely different. This is a smart object that encapsulates a string. Using std::stringinstead of C-strings can make your life loads easier, even though they've got some rough edges and a lot of nasty gotchas; they're well worth looking into, but they're not relevant to the question.

string*是指向std::string对象的指针,并且完全不同。这是一个封装字符串的智能对象。使用std::string代替 C 弦可以让你的生活更轻松,即使它们有一些粗糙的边缘和很多讨厌的问题;它们非常值得研究,但它们与问题无关。

"String"is a special expression that returns a const char*pointing at the specific C-string (note: this is not actually true, but it's a simplification that lets me answer the question concisely).

"String"是一个特殊的表达式,它返回一个const char*指向特定 C 字符串的指针(注意:这实际上不是真的,但它是一种简化,让我可以简洁地回答这个问题)。

A char*can be automatically cast to a const char*, but not vice versa. Note that old C++ compilers had a special exception to the type rules to let you do this:

Achar*可以自动转换为 a const char*,但反之则不然。请注意,旧的 C++ 编译器对类型规则有一个特殊的例外,可以让您这样做:

char* s = "String";

...without producing a type error; this was for C compatibility. Modern C++ compilers won't let you do it (such as recent gccs). They require this:

...不会产生类型错误;这是为了 C 兼容性。现代 C++ 编译器不允许您这样做(例如最近的 gcc)。他们要求:

const char* s = "String";

So. The problem here is that you've got:

所以。这里的问题是你有:

throw "All parameters must be greater than 0.";

...but then you're trying to catch it with:

......但是你试图抓住它:

catch(char* e)

This doesn't work, because the throw is throwing a const char*, which can't be cast to the type specified in the catch, so it isn't getting caught.

这不起作用,因为 throw 正在抛出 a const char*,它无法转换为 catch 中指定的类型,因此它不会被捕获。

This is why changing the catch to:

这就是为什么将捕获更改为:

catch (const char* e)

...makes it work.

...使它工作。

回答by Salgar

Why are you throwing and catching strings anyway?

无论如何,你为什么要扔和接住绳子?

You should throw and catch exceptions, e.g. std::runtime_error

你应该抛出和捕获异常,例如 std::runtime_error

The answer to your question is that whenever you insert a string in quotes in the code it returns a null terminated const char*

您的问题的答案是,每当您在代码中的引号中插入字符串时,它都会返回一个以空字符结尾的 const char*

The reason your code doesn't work as above is because it's the wrong type, so that catch, isn't catching what you're throwing. You're throwing a const char*.

你的代码不能像上面那样工作的原因是因为它是错误的类型,所以 catch 没有捕捉到你抛出的东西。你正在抛出一个 const char*。

There is no limit to the number of characters in a char array beyond the size of your stack/heap. If you're referring to the example you posted, that person had created a fixed size array, so they were limited.

超出堆栈/堆大小的字符数组中的字符数没有限制。如果您指的是您发布的示例,则该人创建了一个固定大小的数组,因此它们是有限的。