I just started to learn C++ and encountered an inconsistency using gnu compiler on the one hand and using Visual C++ and Intel compiler on the other hand. Following example defines a class Person with a pointer to a std::string Name. Within method Person::set the string is assigned by value. I'm sure the better way would be to use a pointer, but that's not the question here.
#include <iostream>
#include <string>
class Person
{
std::string *Name;
public:
Person(std::string *n); //Constructor
void print();
void set(std::string n);
};
Person::Person(std::string *n) : Name(n) //Implementation of Constructor
{
}
// This method prints data of person
void Person::print()
{
std::cout << *Name << std::endl;
}
void Person::set(std::string n)
{
Name = &n;
}
int main()
{
std::string n("Me");
std::string n2("You");
Person Who(&n);
Who.print();
Who.set(n2);
Who.print();
return 0;
}
The gnu compiler gives following result as I would have expected:
Me
You
But the Visual C++ and Intel compilers result in an undefined behviour. I guess the problem is the life time of the copied variable n in Person::set. Why is it still available after finishing Person::set using gnu compiler and not available using Visual C++ and Intel compilers?