在C++类中修改指向std :: string的指针

Hol*_*ger 2 c++ pointers class

我刚开始学习C++和使用中遇到的矛盾gnu,一方面编译器和使用Visual C++,并Intel compiler在另一方面.下面的示例定义了一个Person带有指向std :: string的指针的类Name.在方法内Person::set,字符串由值分配.我确信更好的方法是使用指针,但这不是问题.

#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;
}
Run Code Online (Sandbox Code Playgroud)

gnu编译器给出了我预期的以下结果:

Me
You
Run Code Online (Sandbox Code Playgroud)

但是Visual C++Intel编译器导致了一个不确定的行为.我想这个问题是复制的变量的续航时间nPerson::set.为什么在完成Person::set使用gnu编译器后仍然可用,并且不能使用Visual C++Intel编译器?

jua*_*nza 5

您的Set方法是设置未定义的行为,因为您正在获取局部变量的地址,然后在另一个范围中使用它:

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

正如您所做的那样,任何Name外部取消引用的尝试都是未定义的行为.Person::setPerson::print()

您尝试的所有编译器的行为都与未定义的行为兼容,因为一切都是.