【问题标题】:Heap objects don’t naturally support copy semantics堆对象自然不支持复制语义
【发布时间】:2015-05-20 23:51:01
【问题描述】:

堆对象在 C++ 中自然不支持复制语义是什么意思。我在阅读 CPP 常见问题解答https://isocpp.org/wiki/faq/csharp-java#universal-object 时发现了这一点,但无法理解 C++ 的含义和适用性。

【问题讨论】:

  • IMO 这是一句废话,应该忽略

标签: c++ copy heap-memory semantics


【解决方案1】:
int a = 10;
int b = a;

在上述情况下,a 的值被复制到b。但是考虑一下,

int* c = new int(10);
int* d = c;

在这种情况下,数据不会被复制,但两个指针都指向相同的地址。
如果删除c,则d 指向无效内存。为了避免这种情况, 你需要为d单独分配内存,然后复制数据。

int* c = new int(10);
int* d = new int(*c);

当你有一个有指针的类时,你应该确保你定义了
复制构造函数和赋值运算符,然后处理数据的副本,类似于我在下面显示的方式。

例如,

class A
{
    private:
     int* m_data;

    public:

      A() : m_data(NULL) { }
      A(int x) : m_data(new int(x)) { }
      ~A() { delete m_data; }

      // Failing to provide the below 2 functions will 
      // result in shallow copy of pointers 
      // and results in double delete of pointers.
      A(const A& other) : m_data(new int(*(other.m_data)) { }
      A& operator=(const A& other)
      {
           A temp (other);
            std::swap (m_data, temp.m_data);
           return *this;
      }
};

【讨论】:

  • 谢谢,我明白了,这是shallow copydeep copy 之间的区别,但你能帮我理解与Java 的比较吗?
猜你喜欢
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
相关资源
最近更新 更多