简体   繁体   English

std :: string的奇怪行为

[英]Strange behaviour of std::string

I have this puny program. 我有这个微不足道的程序。

#include    <iostream>
#include    <string>
int main()
{
    std::string st = ('='+"10");
    std::cout<<st<<"-"<<st.c_str();
    return 0;    
}

What sort of output you expect without running it? 您希望在不运行的情况下获得什么样的输出?

I am getting : - 我得到: -

I am running into such problems while using boost::spirit library and passing its output around as c-strings. 我在使用boost :: spirit库并将其输出作为c字符串传递时遇到了此类问题。

Am I missing something? 我想念什么吗? I am using gcc 4.6.1 (ubuntu 10.10). 我正在使用gcc 4.6.1(ubuntu 10.10)。

This: 这个:

'=' + "10"

Probably does not do what you expect. 可能未达到您的期望。 Rather than concatenating, it will "add" (arithmetically) the "ASCII" value of '=' to a pointer to the literal string "10", which is a buffer overrun and so invokes undefined behavior. 而不是连接,它会“算术地”将“ =”的“ ASCII”值“添加”到文字字符串“ 10”的指针,这是缓冲区溢出,因此会调用未定义的行为。

If you run your program under valgrind you will likely see it complain about this. 如果您在valgrind下运行程序,您可能会看到它对此抱怨。

Instead, try: 相反,请尝试:

std::string st = "=";
st += "10";

Try instead: 请尝试:

#include  <iostream>
#include  <string>
int main()
{
    std::string st = ('='+std::string("10"));
    std::cout<<st<<"-"<<st.c_str();
    return 0;
}

Note "10" is a const char* (pointer). 注意"10"是一个const char* (指针)。 Adding to it will increment the pointer using standard integer arithmetic and not concatenate a string. 添加到它会使用标准整数算术来递增指针,而不是连接字符串。

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

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