在函数中,使用容器类变量还是容器类的指针更好?

huangapple go评论65阅读模式
英文:

Is it better to use container class variables or a pointer of container class in function?

问题

在我的程序中,我需要在一个类成员函数中使用多个 `std::vector`  `std::list`:
```cpp
void classA::function(){
   vector<glm::ivec3> tmpContainer[5];
}

或者

void classA::function(){
   vector<glm::ivec3> **tmpContainer;
   tmpContainer = new vector<glm::ivec3>*[5];
   for(int i = 0;i < 5;++i){
       tmpContainer[i] = new vector<glm::ivec3>;
   }
}

哪个更好,两者都可以工作,第一个更方便,但我担心如果 vector 的数量增加到超过 10 个,第一个可能会失败,所以我写了第二个。


<details>
<summary>英文:</summary>

In my program, I need several `std::vector` and `std::list` in a class member function:

void classA::function(){
vector<glm::ivec3> tmpContainer[5];
}

or

void classA::function(){
vector<glm::ivec3> **tmpContainer;
tmpContainer = new vector<glm::ivec3>*[5];
for(int i = 0;i < 5;++i){
tmpContainer[i] = new vector<glm::ivec3>;
}
}

Which is better, both can work, first is convenient, but I&#39;m concerned that if the number of vector increases, more than 10 for example, the first may fail, so I write the second.

</details>


# 答案1
**得分**: 2

你的第一个选择更好,它适合一行,没有泄漏,并且易于阅读。

第二个选择有更多行,更难阅读,包含泄漏和潜在的更多泄漏。请记住,即使在函数后面删除了你分配的元素,如果抛出异常,内存仍然会泄漏。

如果你需要超过5个向量,使用向量的向量。它将清晰、无泄漏且高效。

关于C++有许多“良好的编码规则”,其中之一是永远不要使用“new”。实际上,这不是一个坏主意。

<details>
<summary>英文:</summary>

Your first option is better, it fits in one line, has no leaks and reads easily.

The second one have more lines, is harder to read, contain leaks and potential for more leaks. Remember that even if you delete the elements you allocated later in the function, if an exception is thrown the memory will leak.

If you need more than 5 vectors, use a vector of vectors. It will be clear, leak free, and efficient.

There are many &quot;good style rules&quot; about C++, one of them is to never write &quot;new&quot;. It&#39;s actually not a bad one.

</details>



huangapple
  • 本文由 发表于 2023年7月24日 17:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定