默认assigment operator =在c ++中是一个浅拷贝? [英] Default assigment operator= in c++ is a shallow copy?

查看:115
本文介绍了默认assigment operator =在c ++中是一个浅拷贝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个简单的快速问题,我无法找到一个坚实的答案其他地方。

Just a simple quick question which I couldn't find a solid answer to anywhere else. Is the default operator= just a shallow copy of all the class' members on the right hand side?

Class foo {
public:
  int a, b, c;
};

foo f1, f2;
...
f1 = f2;

将等同于:

f1.a = f2.a;
f1.b = f2.b;
f1.c = f2.c;

这似乎是真的,当我测试它,但我需要确保我不缺少一些具体情况。

This seems to be true when I test it but I need to be sure I'm not missing some specific case.

推荐答案

我会说,默认 operator = 。它复制每个成员。

I'd say, default operator= is a copy. It copies each member.

浅拷贝和深拷贝之间的区别不会出现,除非被拷贝的成员是某种类型的间接,如指针。至于默认的 operator = ,由被复制的成员是什么复制的意思,它可以是深或浅。

The distinction between a shallow copy and a deep copy doesn't arise unless the members being copied are some kind of indirection such as a pointer. As far as the default operator= is concerned, it's up to the member being copied what "copy" means, it could be deep or shallow.

具体来说,虽然,复制一个原始指针只是复制指针值,它不做任何事情与referand。因此,包含指针成员的对象默认是浅复制的 operator =

Specifically, though, copying a raw pointer just copies the pointer value, it doesn't do anything with the referand. So objects containing pointer members are shallow-copied by default operator=.

对复制执行克隆操作,所以如果你使用那些无处不在的原始指针,那么默认的 operator = 将执行深拷贝。

There are various efforts at writing smart pointers that perform clone operations on copying, so if you use those everywhere in place of raw pointers then the default operator= will perform a deep copy.

如果你的对象有任何标准容器作为成员,那么(例如)Java程序员可能会说 operator = 浅拷贝。在Java中, Vector 成员只是一个引用,所以shallow copy意味着 Vector :源和目标是指相同的底层向量对象。在C ++中,一个向量成员将被复制,连同其内容,因为成员是一个实际对象而不是引用(和 vector :: operator = 保证内容被复制)

If your object has any standard containers as members, then it may be confusing to (for example) a Java programmer to say that operator= is a "shallow copy". In Java a Vector member is really just a reference, so "shallow copy" means that Vector members aren't cloned: source and destination refer to the same underlying vector object. In C++ a vector member will be copied, along with its contents, since the member is an actual object not a reference (and vector::operator= guarantees the contents are copied with it).

如果你的数据成员是一个指针的向量,没有深度副本。你有一个半深的副本,其中源和目标对象有独立的向量,但每个静态对应的向量元素指向同一个未克隆的对象。

If your data member is a vector of pointers, then you don't have either a deep copy or a shallow copy. You have a semi-deep copy, where the source and destination objects have separate vectors, but the corresponding vector elements from each still point to the same, uncloned object.

这篇关于默认assigment operator =在c ++中是一个浅拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆