C++ 写深拷贝——拷贝指针值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1936942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a deep copy - copying pointer value
提问by Anonymous
In writing a copy constructor for a class that holds a pointer to dynamically allocated memory, I have a question.
在为包含指向动态分配的内存的指针的类编写复制构造函数时,我有一个问题。
How can I specify that I want the value of the pointer of the copied from object to be copied to the pointer of the copied to object. Obviously something like this doesn't work...
如何指定我希望将复制自对象的指针的值复制到复制到对象的指针。显然这样的事情不起作用......
*foo = *bar.foo;
because, the bar object is being deleted (the purpose of copying the object in the first place), and this just has the copied to object's foo point to the same place.
因为, bar 对象正在被删除(首先复制对象的目的),而这只是将复制到对象的 foo 指向同一个地方。
What is the solution here? How can I take the value of the dynamically allocated memory, and copy it to a different address?
这里的解决方案是什么?如何获取动态分配内存的值,并将其复制到不同的地址?
回答by Nikola Smiljani?
You allocate new object
您分配新对象
class Foo
{
Foo(const Foo& other)
{
// deep copy
p = new int(*other.p);
// shallow copy (they both point to same object)
p = other.p;
}
private:
int* p;
};
回答by Tim Lovell-Smith
I assume your class looks like this.
我假设你的课看起来像这样。
class Bar {
Foo* foo;
...
}
In order to do a deep copy, you need to create a copyof the object referenced by 'bar.foo'. In C++ you do this just by using the new
operator to invoke class Foo's copy constructor:
为了进行深度复制,您需要创建“bar.foo”引用的对象的副本。在 C++ 中,您只需使用new
运算符调用类 Foo 的复制构造函数即可完成此操作:
Bar(const Bar & bar)
{
this.foo = new Foo(*(bar.foo));
}
Note: this solution delegatesthe decision of whether the copy constructor new Foo(constFoo &) also does a 'deep copy' to the implementation of the Foo class... for simplicity we assume it does the 'right thing'!
注意:此解决方案委托决定复制构造函数 new Foo(constFoo &) 是否也对 Foo 类的实现进行“深度复制”……为简单起见,我们假设它做的是“正确的事情”!
[Note... the question as written is very confusing - it asks for the 'value of the pointer of the copied from object' that doesn't sound like a deep copy to me: that sounds like a shallow copy, i.e. this.
[注意...所写的问题非常令人困惑-它要求“从对象复制的指针的值”,这对我来说听起来不像是深拷贝:这听起来像是浅拷贝,即这个。
Bar(const Bar & bar)
{
this.foo = bar.foo;
}
I assume this is just innocent confusion on the part of the asker, and a deep copy is what is wanted.]
我认为这只是提问者的无辜混淆,并且需要一个深层副本。]
回答by Michael Krelin - hacker
I do not see the context, but the code you posted doesn't seem like copying the pointer, it is exactly what you ask for — copying whatever it points to. Provided that foo points to the allocated object.
我没有看到上下文,但是您发布的代码似乎不像复制指针,这正是您所要求的 - 复制它指向的任何内容。只要 foo 指向分配的对象。