Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify pointer to std::string inside C++ class

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?

like image 455
Holger Avatar asked Nov 25 '25 16:11

Holger


1 Answers

Your Set method is setting you up undefined behaviour because you are taking the address of a local variable, and then use it in another scope:

void Person::set(std::string n)
{
    Name = &n; // n is a local variable
}

Any attempt to de-reference Name outside of Person::set, as you do in Person::print(), is undefined behaviour.

The behaviour of all the compilers you tried is compatible with undefined behaviour, because everything is.

like image 68
juanchopanza Avatar answered Nov 28 '25 06:11

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!