In short: No.
Long version: Yes it will work for a while (the length of that while depending on the size of your images) but then will lead to undefined behavior.
The code snippet you posted is actually a recipe for a memory leak, because - as you pointed out correctly in the code comments - the contents of the imgVec
will not automatically self-destroy.
The “type” IMG
is just a typedef
for void *
which should make it obvious that any advanced technique like shared ownership or scoped lifetime cannot be represented on the syntactic level of the code, but must be achieved at run time instead - in your case by making sure that for every IMG
that has been pushed to the std::vector
there is a ReleaseObject
call that disposes of it, otherwise a memory leak is the inevitable consequence.
So at the very least, the code snippet should be modified like this:
std::vector<IMG> imgVec;
for(int i=0; i<n; ++i){
IMG tmpImg;
CreateGenericImage(1, 400, 300, false, tmpImg);
imgVec.push_back(imgVec);
}
// ... do sth with imgVec
...
// cleanup
std::for_each(imgVec.begin(), imgVec.end(), [](IMG& v){ ReleaseObject(v); });
Of course the overall construct is quite a way from elegant, and other solutions are available to those who are willing to invest the time to implement them. For example you might want to have a look at the CvbHandle
smart pointer class that @parsd suggested in this post. A class modeled like this would be suitable for use in a std::vector
and lends itself to the implementation of many useful patterns in C++.
As we are aware of these limitations of the classic C-API we are currently working on an object oriented wrapper not only for C++ but also for Python and C# that will provide a more high-level and easy-to-use access to the functionality of :cvb:. A preview should be available on this forum around autumn.