c_str() vs std::string - 这段小代码的真正区别是什么?
c_str() vs std::string - what's the real difference in this piece of small code?
为什么下面的代码打印 "NO"?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
const std::string abc = "hello";
if (abc.c_str() == "hello")
{
cout << "\nYES";
}
else
{
cout << "NO";
}
}
.c_str()
returns const char*
而 "hello"
应解释为 const char*
或 std::string
,两者均有效。但是为什么不打印"YES"。 strcmp()
在使用时确实打印 "YES"。但是我的问题是关于上面的代码,这是编译器错误吗?
abc.c_str()
是指向 abc
对象的内部缓冲区的指针,然后您要与字符串文字 "hello" 进行指针比较,其中 returns false
.
"hello" should be interpreted as either const char* or std::string both are valid.
没有。 "hello"
永远不会被解释为 std::string
。它的类型为 const char[6]
,在本例中被转换为 const char*
。这种数组转换称为衰减。
But why doesn't it print YES.
当你比较两个指针时,你比较的是它们是否指向同一个对象。您使用的指针比较不相等,因为字符串文字和 std::string
的缓冲区不是同一个对象。
is this a compiler bug?
没有。这是您代码中的错误。
so what would you suggest as the right approach with using c_str() and std::string?
比较空字符数组内容的正确方法是std::strcmp
。
或者,您可以直接对 std::string
使用比较运算符,而不使用 c_str
返回的指针。 std::string
的比较运算符与空终止字符串的内容进行比较。
这不是编译器错误。 abc.c_str()
为您提供指向 std::string
数据缓冲区的指针的值,并且自 C++11 以来,它不可能与文字 "hello"
的地址相同该标准禁止 std::string
的 copy-on-write 语义。 (出于兴趣,我相信这在理论上在 C++03 和更早版本中是可行的。)
如果要将文字与 std::string
进行比较,请使用
if (abc == "hello")
因为 std::string
对 ==
运算符有适当的重载。
你比较的方式不对,试试:
而不是:
if (abc.c_str() == "hello")
使用:
if (!strcmp(abc.c_str(), "hello"))
为什么下面的代码打印 "NO"?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
const std::string abc = "hello";
if (abc.c_str() == "hello")
{
cout << "\nYES";
}
else
{
cout << "NO";
}
}
.c_str()
returns const char*
而 "hello"
应解释为 const char*
或 std::string
,两者均有效。但是为什么不打印"YES"。 strcmp()
在使用时确实打印 "YES"。但是我的问题是关于上面的代码,这是编译器错误吗?
abc.c_str()
是指向 abc
对象的内部缓冲区的指针,然后您要与字符串文字 "hello" 进行指针比较,其中 returns false
.
"hello" should be interpreted as either const char* or std::string both are valid.
没有。 "hello"
永远不会被解释为 std::string
。它的类型为 const char[6]
,在本例中被转换为 const char*
。这种数组转换称为衰减。
But why doesn't it print YES.
当你比较两个指针时,你比较的是它们是否指向同一个对象。您使用的指针比较不相等,因为字符串文字和 std::string
的缓冲区不是同一个对象。
is this a compiler bug?
没有。这是您代码中的错误。
so what would you suggest as the right approach with using c_str() and std::string?
比较空字符数组内容的正确方法是std::strcmp
。
或者,您可以直接对 std::string
使用比较运算符,而不使用 c_str
返回的指针。 std::string
的比较运算符与空终止字符串的内容进行比较。
这不是编译器错误。 abc.c_str()
为您提供指向 std::string
数据缓冲区的指针的值,并且自 C++11 以来,它不可能与文字 "hello"
的地址相同该标准禁止 std::string
的 copy-on-write 语义。 (出于兴趣,我相信这在理论上在 C++03 和更早版本中是可行的。)
如果要将文字与 std::string
进行比较,请使用
if (abc == "hello")
因为 std::string
对 ==
运算符有适当的重载。
你比较的方式不对,试试:
而不是:
if (abc.c_str() == "hello")
使用:
if (!strcmp(abc.c_str(), "hello"))