写入深拷贝 - 复制指针值 [英] Writing a deep copy - copying pointer value

查看:121
本文介绍了写入深拷贝 - 复制指针值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在写一个包含动态分配内存指针的类的复制构造函数时,我有一个问题。

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;

因为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.

这里的解决方案是什么?

What is the solution here? How can I take the value of the dynamically allocated memory, and copy it to a different address?

推荐答案

分配新对象

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;
};

这篇关于写入深拷贝 - 复制指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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