I am facing some strange problem in C++ execution. My project is big where I have used pass by reference in several places but I am showing you a sample of the issue you can test easily.
I wrote this simple program and tested it below under GCC version: v4.9.2 and v5.4.0. I get different behavior esp. when passing std::string with and without reference. In this program, I simply add two entries to a map and find the value for a key. The problem is with map::find(..). I expect consistent behavior irrespective of any gcc compiler version used.
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)
Why is such a case? Is there something wrong with the program or is that a compiler bug somewhere? The program below should compile as is.
// 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;
}
I would have expected FOUND and FOUND under any gcc compiler. See the example running fine under GCC v4.9.2 here or add the above code on cpp.sh (uses v4.9.2). For compiler v5.4.0, you can test this on Ubuntu or elsewhere appropriately.