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
编译器导致了一个不确定的行为.我想这个问题是复制的变量的续航时间n
在Person::set
.为什么在完成Person::set
使用gnu
编译器后仍然可用,并且不能使用Visual C++
和Intel
编译器?
您的Set
方法是设置未定义的行为,因为您正在获取局部变量的地址,然后在另一个范围中使用它:
void Person::set(std::string n)
{
Name = &n; // n is a local variable
}
Run Code Online (Sandbox Code Playgroud)
正如您所做的那样,任何Name
外部取消引用的尝试都是未定义的行为.Person::set
Person::print()
您尝试的所有编译器的行为都与未定义的行为兼容,因为一切都是.
归档时间: |
|
查看次数: |
466 次 |
最近记录: |