Passing around fixed-size arrays in C++?
Basically I'd like to do something like that:
int[3] array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
int[3] point=array_func();
}
But that doesn't seem legal in C++. I know I 开发者_运维问答can use vectors, but since I know the size of the array is a constant, it seems like a loss of performance is likely to occur.
I'd also like to avoid a new
if I can, because allocating stuff on the stack is easier and also likely to improve performance.
What's the solution here?
Using C++0x, the almost finalized new C++ standard (already implemented in latest gcc and msvc IIRC), you can do it exactly as you want! Simply use std::array instead of int[3].
std::array<int, 3> array_func()
{
return {1,1,1};
}
int main(int argc,char * argv[])
{
std::array<int, 3> point = array_func();
}
Put the array into a struct. boost::array
is such a package:
boost::array<int, 3> array_func() {
boost::array<int, 3> a = {{ 1, 1, 1 }};
return a;
}
int main() {
boost::array<int, 3> b = array_func();
}
Quick and dirty:
template<typename E, size_t S>
struct my_array {
E data[S];
};
Notice how you can use aggregate initialization syntax.
You can wrap it in a struct
, to make it returnable by value:
struct Vec3
{
float x[3];
}
Vec3 array_func()
{
Vec3 x = { 1.f, 1.f, 1.f };
return x;
}
I don't think you can use the array initializer syntax directly in the return statement. Of course you could introduce a constructor (structs are just classes with all members public, after all):
struct Vec3
{
Vec3(a, b, c)
{
x[0] = a;
x[1] = b;
x[2] = c;
}
float x[3];
}
Vec3 array_func()
{
return Vec3(1.f, 1.f, 1.f);
}
you can't return a fixed size array in C++. you may return a pointer to int (which would be used as an array) but that would require allocating the array on the heap using new
.
anyway, you can pass your array as an argument to your function:
void array_func( int result[3])
{
result[0] = 1;
result[1] = 1;
result[2] = 1;
}
int main(int argc,char * argv[])
{
int point[3];
array_func( point );
}
however, this looks more like C than C++...
boost::array is a wrapper for a stack-based array.
Note that stack allocation is only going to stay cheaper than using 'new' when you're not having to copy large arrays around.
精彩评论