英文:
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'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 "good style rules" about C++, one of them is to never write "new". It's actually not a bad one.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论