Re: passing unnamed array to function
poorboywilly <j.craig@aggiemail.usu.edu> wrote in news:5b04358b-3510-
4354-a66b-cc392f54e5ac@h11g2000prf.googlegroups.com:
I've been unable to find any information on this through any search
engines. Is there any way to pass an unnamed (temporary) array to a
function?
e.g.
void f0(const int ar[5]);
void f1(const int ar[]);
f0( {1, 2, 3, 4, 5} ); //does not compile
f1( {1, 2, 3} ); //does not compile
int n_set[] = {1, 2, 3, 4, 5};
f0(n_set); //these both compile (of course)
f1(n_set);
I know I can use an STL container instead and pass an unnamed STL
container, but an STL container doesn't allow me to set construct it
with, say, 5 arbitrary values.
So I guess my question is, why can I not initialize a function
argument with the array "shorthand" notation, and is there an
alternative syntax that will allow this?
The short answer is because the C++ syntax doesn't allow it. The longer
answer is that in general, objects have to exist somewhere. In the case
of temporary objects, this is normally on the stack, though compilers
are allowed to put them anywhere. Thing is, after the temporary goes
out of scope, the memory is reclaimed. This doesn't leave a lot of
options for temporary arrays. Most of the languages which allow what
you wrote also have garbage collectors tightly integrated with the
language. This more easily allows temporaries to be put in the garbage
collected heap, because you don't have to worry about leaking the
allocated memory. This kind of tight integration with a garbage
collector will never be the case in C++.
You could look at the 'assign' library in boost. It lets you write
things like.
std::vector<int> v;
v += 1,2,3,4,5;
And a few other collection initializing tricks.
HTH,
joe