C ++:自动向量重分配调用复制构造函数?为什么? [英] C++: Automatic vector reallocation invokes copy constructors? Why?

查看:191
本文介绍了C ++:自动向量重分配调用复制构造函数?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读C ++ Primer,第3版(Lippman和Lajoie),它说,当一个向量需要重新分配,以便为更多的元素添加 push_back(),元素在新空间中被复制构造,然后在旧元素上调用析构函数。我很困惑为什么这是必要的 - 为什么数据不能被逐位复制?我假设答案与动态内存分配有关,但我目前的推理是,即使向量元素处理动态内存,实际存储在元素中的数据将是指针,这意味着按位复制将保留它们指向的位置并且不会出现任何问题。我可以看到如何重新定位元素所指向的动态分配的内存将是一个问题,因为它会使指针无效,但就我可以告诉向量重定位将没有理由这样做。

I'm reading C++ Primer, 3rd Ed (Lippman and Lajoie) and it's saying that when a vector needs to be reallocated in order to make space for more elements added with push_back(), the elements are copy-constructed in the new space and then the destructor is called on the old elements. I'm confused about why this is necessary - why can't the data just be copied bit-for-bit? I assume that the answer has to do with dynamic memory allocation, but my current line of reasoning is that even if the vector elements handle dynamic memory, the data actually stored in the elements will be pointers, meaning bitwise copying will preserve the location they point to and won't present any problems. I can see how re-locating the dynamically-allocated memory that the elements point to would be a problem, since it would invalidate the pointers, but as far as I can tell the vector re-location would have no reason to do that.

有人可以给我一个类的简单示例,不应该逐个移动?

Can someone give me a simple example of a class which shouldn't be moved bit-by-bit?

推荐答案

这里可能是最简单的(但是很麻烦)的例子:

Here's probably the simplest (but rather contrived) example:

class foo
{
  int i;
  int* pi; // always points to i
};

这里,复制构造函数将保持 pi 指向 i 。编译器本身将无法自己找出这种关系,因此需要调用复制构造函数。

Here, the copy constructor would maintain the invariant that pi points to i. The compiler itself wouldn't be able to figure out this relationship on its own, hence the need to call the copy constructor.

这篇关于C ++:自动向量重分配调用复制构造函数?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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