std :: vector如何将对象复制到其内部存储 [英] How does std::vector copy objects to its internal storage

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

问题描述

我有以下问题:

void add(){
  cRow Row();
  Row.add("Column", "Value");
  std::vector<cRow> mRows;
  mRows.push_back(Row);
}

cRow::cRow(): mCol(NULL), mVal(NULL) {
}

cRow::add(const char* Col, const char* Val){
  mCol = strdup(Col);
  mVal = strdup(Val);
}

cRow::~cRow(){
  free(mCol);
  free(mVal);
}

将局部变量Row添加到向量后,将为该Row调用析构函数,并释放字符串.

After adding the local variable Row to the vector, the destructor is called for that Row and the strings are freed.

很显然,指向向量中存储行的字符串的指针现在也已释放.离开本地范围后对行的任何访问都将导致段错误.

Obviously, the pointers to the strings of the stored row in the vector are now freed as well. Any access to the rows after leaving the local scope will result in segfaults.

该行的转储会照这样进行2次调用:

The dump of the rows looks after 2 calls like that:

| (null) | (null)  |
-----------------------------------------------------
| (null)| (null) |
| LastContainerUpdatePropagation| 1307967498 |
------------------------ END ------------------------

3次通话后

| (null) | (null)  |
-----------------------------------------------------
| (null)| (null) |
| (null)| (null) |
| LastSystemUpdatePropagation| 1307967498 |
------------------------ END ------------------------

,并且在完全不添加新行的情况下离开了范围,然后释放了每一行.

and after leaving the scope completely without adding a new row, every row was freed.

那么,现在我的问题是:std:vector如何复制对象?我该怎么做才能保持指向字符串的指针或将其复制到另一个空间?

So, now my question: How does std:vector copy objects? What do I have to do to keep the pointers to the strings or to copy them into another space?

非常感谢!

推荐答案

std::vector使用复制构造函数复制对象.由于您尚未定义副本构造函数,因此它将使用隐式C ++副本构造函数,只是递归地复制所有成员;这还不够,因为您正在手动管理内存.

std::vector uses the copy constructor to copy objects. Since you have not defined a copy constructor, it will use the implicit C++ copy constructor, which just copies all members recursively; this isn't enough, since you are manually managing memory.

您需要定义自己的副本构造函数,或者使用类似std::string的东西,如果被复制,它将做正确的事情.

You need to either define your own copy constructor, or use something like std::string, which will do the right thing if copied.

出于良好实践的考虑,正是由于这个原因,任何具有非平凡析构函数的类都应具有一个拷贝构造函数和一个拷贝赋值运算符(这称为

As a matter of good practice, any class with a non-trivial destructor should have a copy constructor and copy assignment operator, for precisely this reason (this is known as the rule of three). If a copy constructor doesn't make sense (eg, for things like ostream), it should be made private, in order to prevent accidental copying.

这篇关于std :: vector如何将对象复制到其内部存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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