为什么在 c++ 向量中使用 new 调用? [英] Why use a new call with c++ vector?

查看:81
本文介绍了为什么在 c++ 向量中使用 new 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码 vectormyVector; 动态分配内存,因此任何存储的元素将一直存在,直到调用删除.那么下面的 vector 怎么样?*myVector = new vector<someType>();,与之前的不同(除了是一个指针)?

The code vector<someType> myVector; dynamically allocates memory, so any elements stored will live until a delete is called. So how is the following, vector<someType> *myVector = new vector<someType>();, different (other than being a pointer) from the earlier one?

这里是否发生了双重分配?每个人都提到将 vectornew 调用混合在一起是邪恶的,但为什么呢?如果它是邪恶的,为什么它是编译器可以接受的代码,什么时候可以使用?

Is there a double allocation happening here? Everyone mentions it is evil to mix a vector with a new call, but why? If it is evil, why is it acceptable code for the compiler and when is it okay to use?

推荐答案

你的第一句话不正确.vector 中的元素myVector 将一直存在,直到向量被销毁.如果 vector 是局部变量,当它超出作用域时会自动销毁.您不需要显式调用 delete.如果您考虑到由于可能会抛出异常,您的 delete 语句可能永远不会到达,从而导致内存泄漏,那么显式调用 delete 很容易出错.例如.比较以下两种情况

Your first statement is not true. The elements in vector<someType> myVector will live until the vector is destroyed. If vector<someType> is a local variable, it will be destroyed automatically when it goes out of scope. You don't need to call delete explicitly. Calling delete explicitly is error-prone if you take into account that because of exceptions that might be thrown, your delete statement may never be reached, leading to memory leaks. E.g. compare the following two cases

void foo()
{
   std::vector<int> v;
   v.push_back(1);
   f(); // f is some operation that might throw exception.
}  // v is automatically destroyed even if f throws.

void bar()
{
   std::vector<int>* v = new std::vector<int>;
   v->push_back(1);
   f(); // f is some operation that might throw exception.
   delete v;  // You need to call delete explicitly here.
              // The vector will be destroyed only if f doesn't throw.
}

除上述之外,向量确实会动态分配内存来存储新元素.两种情况的区别在于:

Apart from the above, it's true that a vector dynamically allocates memory to store new elements. The difference between the two cases is:

  • std::vectorv v 是堆栈上的一个对象,它动态分配内存以存储元素.

  • std::vector<int> v v is an object on the stack, that dynamically allocates memory in order to store elements.

std::vector* v = new std::vector v 是一个指向动态分配对象的指针,该对象动态分配内存以存储元素.如前所述,您需要显式调用 delete 来销毁此对象.

std::vector<int>* v = new std::vector<int> v is a pointer to a dynamically allocated object, that dynamically allocates memory in order to store elements. As said already, you need to explictly call delete to destroy this object.

这篇关于为什么在 c++ 向量中使用 new 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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