I have a struct Foo
from an external API library, which is in C, and above which I am writing a C++ interface.
So I have a class like this:
class ClassFoo
{
public:
ClassFoo(const Foo * ptr) : ptr(ptr) { }
~ClassFoo();
bool method1();
int method2();
... (other methods)
private:
const Foo * ptr;
}
Then, the external library defines another struct Bar
which is a collection of Foo
s, a method for getting the number of foos, and a method for retrieving an array of Foo*
pointers:
int APIbarGetNumFoos(const Bar* ref);
void APIbarGetFoos(const Bar* ref, int maxSize, const Foo* foos[]);
I define a ClassBar
like this:
class ClassBar
{
public:
ClassBar(const Bar * ptr) : ptr(ptr) { }
~ClassBar();
std::vector<ClassFoo> getFoos();
... (other methods)
private:
const Bar * ptr;
}
Now the question : for memory & speed efficiency, I want to avoid allocating an array of Foo*
to call the C API, then copy everything to the result vector.
Does C++ guarantees that ClassFoo
instance only contains a Foo*
pointer, and that its size is the size of a pointer, if I do not use any virtual methods (to avoid the vtables), so that I can define getFoos()
like that:
std::vector<ClassFoo> ClassBar::getFoos()
{
int size = APIbarGetNumFoos(ptr);
std::vector<ClassFoo> result(size);
APIbarGetFoos(ptr, size, (const Foo**) &result[0]);
return result;
}
In other words, can I be sure that an array of ClassFoo
will be in memory strictly the same as an array of Foo*
?
Thanks!
Etienne