Hello,
Consider the following program. There are two C style string stack variables
and one C style string heap variable. The compiler may or may not optimize
the space taken up by the two stack variables by placing them at the same
address (my g++ compiler does this). Therefore the output of the given
C program is compiler dependent. What is worse, the program does not
do what its writer most likely intended, since, std::set's find()
method uses an implicit == operator for comparison, which in this
case does an address comparison (no way to do an strcmp in this
case seems possible). So the problem is simply solved by using
the string class which was in the mind of the designers of C++
when the STL was created, namely, std::string.
Regards,
Neil
---------------- code follows -------------------------------------------
#include <iostream>
#include <cstdlib>
#include <set>
int main() {
std::set<char *> foo;
foo.insert("hello");
char *bar1 = "hello", *bar2;
if ((bar2 = (char *) malloc(6)) == 0) {
std::cout << "not enough memory" << std::endl;
exit(EXIT_FAILURE);
}
if (foo.find(bar1) != foo.end())
std::cout << "hello" << std::endl;
else
std::cout << "good night" << std::endl;
if (foo.find(bar2) != foo.end())
std::cout << "hello" << std::endl;
else
std::cout << "good night" << std::endl;
}