I just want to make sure there aren’t any potential problems with this. It compiles and runs fine, but am I risking any weird memory effects? Do I need to be especially concerned about exceptions in this case?
//...constructor of some class
myobj(int length, int *vars)
{
// do stuff with vars
}
// inside some other code somewhere
int vars[3] = {5,6,7};
myobj *o = new myobj(3,vars);
(Edit.) I’m just concerned because I know pointers to objects on the stack should always be used with caution. To be specific about my usage, I’d mainly like the fastest way to pass in a variable number of arguments of the same type. So is this a bad way to do it? Thanks..
Postscript. All the answers were very helpful, thanks! I’ll see whether the performance matters enough to use this method, or perhaps if I can solve the problem another way altogether.
There’s nothing inherently wrong with this. However, there are a few things you need to be careful of:
varsaround after you return (or at least, after it goes out of scope).varsis only valid until you leave the scope that it was declared in.varsarray.It’s more common style in C++ to use, e.g. a
std::vector<int> ¶meter, or some other container type. This has two major reasons for it: By passing as a reference, it makes it more obvious that you may not be meant to keep a pointer to the object, and by passing a vector, the size of the array is kept along with the array itself (and you can expand the array if need be as well). However, this is a matter of style, and there is overhead tovector, so if performance is at a premium, this approach is perfectly reasonable.