[英]Weird behavior of default copy constructor in C++
I've encountered a weird behavior during learning about implicit copy constructors in C++. 在学习C ++中的隐式副本构造函数期间,我遇到了一个奇怪的行为。 This is about this bunch of code:
这是关于这堆代码的:
#include <iostream>
class Person
{
public:
char* name;
int age;
Person( const char* the_name, int the_age )
{
name = new char[strlen( the_name ) + 1];
strcpy( name, the_name );
age = the_age;
}
~Person()
{
delete[] name;
}
};
int main(){
Person p1( "Tom", 22 );
Person p2( p1 );
p2.name = "Bill";
// the output is: "Tom"
std::cout << p1.name << std::endl;
std::cin.get();
}
By default, copying an object means copying its members, therefore while creating p2
object using default copy constructor it should copy merely a pointer name
, not the character array it points to. 默认情况下,复制对象意味着复制其成员,因此,在使用默认复制构造函数创建
p2
对象时,它应仅复制一个指针name
,而不是其指向的字符数组。 Therefore changing name
member of object p2
should change the name
member of object p1
. 因此,改变
name
对象的成员p2
应该更改name
对象的成员p1
。 Thereupon p1.name
should be "Bill"
not "Tom"
. 于是
p1.name
应该是"Bill"
而不是"Tom"
。
What's wrong in my reasoning? 我的推理有什么问题? Why it's printing
"Tom"
? 为什么要打印
"Tom"
?
By default, copying an object means copying its members
默认情况下,复制对象意味着复制其成员
Yes. 是。
therefore while creating
p2
object using default copy constructor it should copy merely a pointername
, not the character array it points to.因此,在使用默认复制构造函数创建
p2
对象时,它应该仅复制一个指针name
,而不复制其指向的字符数组。
Correct. 正确。
Therefore changing name member of object
p2
should change the name member of objectp1
.因此,更改对象
p2
的名称成员应更改对象p1
的名称成员。
Nope. 不。 Yes,
p2.name
and p1.name
point to the same memory location, but that doesn't mean that changing the pointer value of p1.name
will change the value of p2.name
. 是的,
p2.name
和p1.name
指向同一个内存位置,但这并不意味着改变的指针值 p1.name
会改变的价值p2.name
。 If that were int
s, would you be surprised if changing p1.name
has no effect p2.name
? 如果那是
int
s,如果更改p1.name
无效p2.name
,您会感到惊讶吗? Because it's the same thing here. 因为这是同一件事。 You have two different variables, and changing one's value doesn't change the value of the other.
您有两个不同的变量,更改一个变量的值不会更改另一个变量的值。
int a = 0;
int b = 1;
int* ptrA = &a;
int *ptrA2 = &a;
*ptrA = 1; // now a == 1
*ptrA2 = 4; // now a == 4
ptrA2 = &b;
*ptrA2 = 10; // now b == 10
*ptrA = 3; // now a == 3, a != 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.