c++ - 具有不同编译器版本的 C++ 中的奇怪行为(字符串通过引用传递): See simple program illustration

标签 c++ string gcc pass-by-reference

<分区>

我在 C++ 执行中遇到了一些奇怪的问题。我的项目很大,我在几个地方使用了引用传递,但我向您展示了一个您可以轻松测试的问题示例。

我编写了这个简单的程序并在 GCC 版本 v4.9.2 和 v5.4.0 下对其进行了测试。我有不同的行为,尤其是。在有和没有引用的情况下传递 std::string 时。在这个程序中,我只是将两个条目添加到一个映射中并找到一个键的值。问题在于 map::find(..)。无论使用何种 gcc 编译器版本,我都希望行为一致。

GCC version: 4.9.2 output: FOUND, FOUND (tested on Raspberry Pi3, http://cpp.sh)

GCC version: 5.4.0 output: NOT FOUND, FOUND (tested on Ubuntu v16.04)

为什么会这样呢?程序有问题还是某处有编译器错误?下面的程序应该按原样编译。

// program.cpp
// Compile using: "g++ -o program program.cpp"

#include <iostream>
#include <string>
#include <map>
#include <stdio.h>
using namespace std;

std::map<const char*,int> mymap;

bool FindWithoutPassByRef(const std::string id_)
{
    const char* id = id_.c_str();

    std::map<const char*, int>::iterator it;
    it = mymap.find(id);

    if (it != mymap.end())
    {
        cout <<"FOUND";
        return true;
    }

    cout <<"NOT FOUND";
    return false;
}

bool FindWithPassByRef(const std::string& id_)
{
    const char* id = id_.c_str();

    std::map<const char*, int>::iterator it;
    it = mymap.find(id);

    if (it != mymap.end())
    {
        cout <<"\nFOUND";
        return true;
    }

    cout <<"\nNOT FOUND";
    return false;
}

int main(int argc, char *argv[])
{
    printf("gcc version: %d.%d.%d\n",__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__);

    const std::string key1 = "key1";
    const std::string key2 = "key2";

    mymap[key1.c_str()] = 50;
    mymap[key2.c_str()] = 60;

    FindWithoutPassByRef(key1); // should print FOUND
    FindWithPassByRef(key1);    // should print FOUND

    cout<< endl;
}

我希望在任何 gcc 编译器下都能找到 FOUND 和 FOUND。 查看在 GCC v4.9.2 下运行良好的示例 here或在 cpp.sh 添加以上代码(使用 v4.9.2)。对于编译器 v5.4.0,您可以在 Ubuntu 或其他适当的地方进行测试。

最佳答案

您正在将指针放在 map 中并尝试将它们与其他指针相匹配。这只会比较那些指针所持有的“内存地址”;它不会比较它们指向的东西(即您的字符串数据)。

当您的指针是指向来自单个 std::string 的数据的指针时,它们很可能是相同的指针(因为数据位于同一位置)。但是,当您的指针指向不同的字符串时,发生这种情况的可能性非常小。

不要将 char 指针放在 map 中。而是比较实际的字符串。

关于c++ - 具有不同编译器版本的 C++ 中的奇怪行为(字符串通过引用传递): See simple program illustration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723435/

相关文章:

c++ - mysql和c++连接

c++ - boost - "static"与 "shared"库

c++ - 获取基于基本策略的模板类特化适用于所有派生策略

c - read() 从文件中返回额外的字符

java - 将此 String 转换为 int 的最佳方法

windows - Windows 7 下 GTK 中 gtk_widget_queue_draw 中的内存泄漏

C++ vector 指针问题/指向 vector 中对象的指针的 vector

c - 使用 ARM gcc 时,LD 给出奇怪的错误并且找不到现有文件

c - GCC/链接器错误 : using extern keyword gives duplicate definition

java - java加密解密中如何将String转换为byte[]?