【发布时间】:2014-12-17 20:42:36
【问题描述】:
我有一个带有一个结构命名样本的程序,它包含 2 个 int 成员和一个 char *。在创建 2 个名为 a 和 b 的对象时,我尝试使用指针为 a 分配一个新的动态字符串,然后将所有值复制到 b。所以b = a。但是稍后当尝试像这样对 a 进行更改时:a.ptr[1] = 'X'; b 中的指针也会更改。我想知道为什么,我该如何解决。
struct Sample{
int one;
int two;
char* sPtr = nullptr;
};
int _tmain(int argc, _TCHAR* argv[])
{
Sample a;
Sample b;
char *s = "Hello, World";
a.sPtr = new char[strlen(s) + 1];
strcpy_s(a.sPtr, strlen(s) + 1, s);
a.one = 1;
a.two = 2;
b.one = b.two = 9999;
b = a;
cout << "After assigning a to b:" << endl;
cout << "b=(" << b.one << "," << b.two << "," << b.sPtr << ")" << endl << endl;
a.sPtr[1] = 'X' ;
cout << "After changing sPtr[1] with 'x', b also changed value : " << endl;
cout << "a=(" << a.one << "," << a.two << "," << a.sPtr << ")" << endl;
cout << "b=(" << b.one << "," << b.two << "," << b.sPtr << ")" << endl;
cout << endl << "testing adresses for a and b: " << &a.sPtr << " & b is: " << &b.sPtr << endl;
return 0;
}
【问题讨论】:
-
你能发布运行这个代码片段的输出吗?
-
将
b赋值给a后,b的所有成员的值都是a中的值的副本,包括指针(指针也是值,只是发生可解释为地址)。所以a和b都有指向内存中相同位置的指针——并且更改该内存与a或b无关,因为它们的所有指针都只是指向那个(相同) 地点。这有帮助吗? -
What is The Rule of Three? 的可能重复项