问题描述
大家好,
我有一个虚函数,应该返回一个整数数组.
在该函数的各种实现中,数组长度是不同的.
我的问题是声明这样一个函数的正确方法是什么?
我当前的清醒是
Hi all,
I have a virtual function that should return an array of ints.
The array length is different in the various implementations of the function.
My question is what is the right way to declare such a function?
My current decleration is
int* MyFunc(int &iNumberOfElements)
其中iNumberOfElements是返回数组中的元素数.
每个函数实现均返回不同的数组.
还有另一种更智能"的方法吗?可以通过功能a
指向int的指针,并以某种方式将数组复制到它(如何?)
谢谢
dj4400
where iNumberOfElements is the number of elements in the returned array.
Each function implementation returns a different array.
Is there another "smarter" way to do it? may be pass the function a
pointer to int and copy the array to it in some way (how?)
Thanks
dj4400
推荐答案
A do_something_RVO()
{
....
return A( param );
}
或
or
A do_something_NVRO()
{
A value;
....
return value;
}
可以摆脱分配返回值的任何副本构造.如今,大多数编译器如果不考虑下载支持gcc 4.x的VC ++ 2010 Express,就支持这些优化.
can get rid of the copy construction of whatever the return value is assigned to. These days most compilers support these optimisations, if they don''t consider downloading either VC++ 2010 express of gcc 4.x which do.
int MyFunc(int** pointerToFill)
{
*pointerToFill = new int;
return numElements;
}
HRESULT MyFunc(int** pointerToFill, int& iNumElements)
{
*pointerToFill = new int;
iNumElements = numElements;
return SUCCESS;
}
我认为真的没有更智能"的方式.
用std::vector
替换常规数组实际上并不会引起很多问题.您仍然可以将其与数组完全相同地使用,但不必使用额外的变量来存储元素的数量,它将包含数字本身,并且您不必担心分配和释放内存.要节省一些键入内容,您还可以设置typedef
.
I don''t think there really is a ''smarter'' way.
Replacing the regular array with an std::vector
shouldn''t really cause that many problems though. You can still use it exactly the same as an array but instead of having an extra variable to store the number of elements it will contain the number itself and you don''t need to worry so much about allocating and freeing memory. To save a little typing you can also set up a typedef
.
typedef std::vector<int> MyIntArra
std::vector<int> MyFunc()</int>
这样,您不必返回作为out参数返回的项目数, std:vector
会知道它持有多少个项目.
希望这会有所帮助,
弗雷德里克(Fredrik)
That way you don''t have to return the number of items returned as an out parameter, the std:vector
will know how many items it''s holding.
Hope this helps,
Fredrik
这篇关于从函数返回指向数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!