【发布时间】:2014-05-02 08:40:55
【问题描述】:
我刚开始学习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;
}
gnu 编译器如我所料给出以下结果:
Me
You
但是Visual C++ 和Intel 编译器会导致未定义的行为。我猜问题是Person::set 中复制变量n 的生命周期。为什么使用gnu编译器完成Person::set后仍然可用,而使用Visual C++和Intel编译器则不可用?
【问题讨论】: