I have a third party API that expects me to pass a std::string
by reference. It says it is accepting it with const
. That pretty much means nothing because it can just cast the memory pointer to a non-const char*
and modify my string.
Check the code below with an example.
Should I be concerned/suspicious about third-party APIs that ask me to pass a const std::string&
(by const reference) instead of a std::string
(by value)?
They told me it is because they want to avoid string copying as the strings can be long. Am I being paranoid or it makes sense?
class Blah {
public:
static void testBlah(const string& s) {
char* blah = (char*) s.c_str(); // cast away from const char*
blah[1] = 'b';
}
};
int main() {
cout << "!!!Hello There !!!" << endl; // prints !!!Hello World!!!
const string s = "xxx"; // NOTE THE CONST !!!
Blah::testBlah(s);
cout << s << endl; // prints "xbx"
return 0;
}
Just wrap it in your own trusted class:
#include <iostream>
class Blah {
public:
static void testBlah(const std::string& s)
{
char* blah = (char*)s.c_str(); // cast away from const char*
blah[1] = 'b';
}
};
class Safe_Blah {
public:
static void testBlah(const std::string s)
{
Blah::testBlah(s);
}
};
int main()
{
std::cout << "!!!Hello There !!!" << std::endl; // prints !!!Hello World!!!
const std::string s = "xxx"; // NOTE THE CONST !!!
//Blah::testBlah(s);
Safe_Blah::testBlah(s);
std::cout << s.c_str() << std::endl; // now prints "xxx"
return 0;
}