std::vector 内存处理 [英] std::vector memory handling

查看:52
本文介绍了std::vector 内存处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着用谷歌搜索我的问题的答案,但我找不到任何有效的解释,因此我在这里发布我的问题.以下是我的示例代码和输出:

I tried to google and search an answer to my question, but I couldn't find any valid explanation hence I am posting my question here. Following is my sample code and output:

#include <iostream>
#include "vector"
using namespace std;

typedef struct Node{
    int data;
    Node(){
        data = 0;
        std::cout << "Node created. " << this <<'\n';
    }
    ~Node(){
        data = 0;
        std::cout << "Node destroyed. " << this <<'\n';
    }
} Node;

int main() {
    std::vector<Node> vec;
    for(int i = 0; i < 2 ; i++)
       vec.push_back( *(new Node));
    return 0;
}

输出:

Node created. 0x9e0da10
Node created. 0x9e0da30
Node destroyed. 0x9e0da20
Node destroyed. 0x9e0da40
Node destroyed. 0x9e0da44

为什么会有额外的销毁,为什么创建的对象与销毁的对象不同?

Why is there an extra destroy and why are created objects different from destroyed object?

推荐答案

如果你添加一个复制构造函数,你会找到答案:

If you would add a copy constructor you would find out the answer:

Node created. 0x60200000df90
Node copied: 0x60200000df70  Source: 0x60200000df90
Node created. 0x60200000df50
Node copied: 0x60200000df34  Source: 0x60200000df50
Node copied: 0x60200000df30  Source: 0x60200000df70
Node destroyed. 0x60200000df70
Node destroyed. 0x60200000df34
Node destroyed. 0x60200000df30

因此,当您将第二个元素添加到向量时,将没有足够的容量,向量必须调整存储大小并将所有旧元素(在这种情况下只有一个这样的元素)复制到新空间.这就是为什么要调用一个额外的复制构造函数.

So when you have added the second element to the vector there will not be enough capacity and the vector has to resize the storage and copy all old elements (in this case only one such element) to the new space. That's why one extra copy constructor was called.

是的,在 C++ 中,所有标准容器都要求对象应该是可复制或移动构造的,因此您不必在堆上创建它们(如在 Java 中).更正确的代码如下:

And yes, in C++ all standard containers requires that object should be copy or move constructible, so you don't have to create them on the heap (as in Java). The more correct code would be like:

#include <iostream>
#include "vector"


struct Node {
  int data;
  Node() : data(0) {
    std::cout << "Node created. " << this <<'\n';
  }

  Node(const Node &n) : data(n.data) {
    std::cout << "Node copied: " << this << "  Source: " << &n << std::endl;
  }

  ~Node(){
    // You don't need data = 0 in destructor
    std::cout << "Node destroyed. " << this <<'\n';
  }

};

int main() {
  std::vector<Node> vec;
  for(int i = 0; i < 2 ; i++) {
    vec.push_back(Node());
  }
  return 0;
}

这篇关于std::vector 内存处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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