如何返回CArray?
哪种方式适合返回类数组?
class BigSizeClass {
int data[1024 * 1024];
};
非常糟糕且昂贵的方式:
CArray
;测试() { CArray ret; for(int i = 0; i < 1024; i++) { 大尺寸类c; ret->添加(c); } 返回ret; } 可能是我忘记删除返回值:
CArray
* test() { CArray * ret = new CArray (); for(int i = 0; i < 1024; i++) { 大尺寸类c; ret->添加(c); } 返回ret; } 可能是我确实喜欢昂贵:
// CArray
; r = 测试(); -->昂贵的 // CArray & r = 测试(); -->不贵(正确 - 因为 &) CArray &测试() { CArray * ret = new CArray (); for(int i = 0; i < 1024; i++) { 大尺寸类c; ret->添加(c); } 返回*ret; } 可能是我忘记删除对象:
CArray
;测试() { CArray ret; for(int i = 0; i < 1024; i++) { BigSizeClass* c = 新 BigSizeClass; ret->添加(c); } 返回ret; }
Which way is good for returning an array of classes?
class BigSizeClass {
int data[1024 * 1024];
};
Very bad and expensive way:
CArray<BigSizeClass> test() { CArray<BigSizeClass> ret; for(int i = 0; i < 1024; i++) { BigSizeClass c; ret->Add(c); } return ret; }
may be I forget delete returning value:
CArray<BigSizeClass>* test() { CArray<BigSizeClass>* ret = new CArray<BigSizeClass>(); for(int i = 0; i < 1024; i++) { BigSizeClass c; ret->Add(c); } return ret; }
may be I do like Expensive:
// CArray<BigSizeClass> r = test(); --> Expensive // CArray<BigSizeClass>& r = test(); --> Not Expensive (Correct - because of &) CArray<BigSizeClass>& test() { CArray<BigSizeClass>* ret = new CArray<BigSizeClass>(); for(int i = 0; i < 1024; i++) { BigSizeClass c; ret->Add(c); } return *ret; }
may be I forget remove objects:
CArray<BigSizeClass*> test() { CArray<BigClassSize> ret; for(int i = 0; i < 1024; i++) { BigSizeClass* c = new BigSizeClass; ret->Add(c); } return ret; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法1就好了。 RVO 和 NRVO 将在此发挥作用。即使没有,您仍然可以“交换”,假设 CArray 做了聪明的事情并且具有交换功能。
但是,我不得不建议不要使用 CArray - 它不使用复制构造函数,而是使用 memcpy,这对于任何非 POD 类来说都是可怕的未定义行为。
Way 1 is just fine. RVO and NRVO will kick in here. Even if it doesn't you can still "swaptimize", assuming that CArray does the smart thing and has a swap function.
However, I'd have to recommend against the use of CArray- it doesn't use the copy constructor but instead uses
memcpy
, which is hideously undefined behaviour for any non-POD classes.在 C++11 中,您可以使用 R 值引用。不幸的是,
CArray
不是用右值语义实现的。您应该使用可识别 R 值/移动语义的 STL 容器。如果可以使用 R 值,您可以从函数返回整个向量- 向量类将负责复制(移动)返回的向量。
In C++11 you may use R-value references. Unfortunately
CArray
isn't implemented with r-value semantics. You should use STL containers which are R-value/move-semantics aware.You may, if R-Value can be used, return entire
vector<BigSizeClass>
from the function - vector class would take care of copying (moving) the returned vector.