I have a dll or shared object, MyDll which produces an object, ForeignObject:
class ForeignObject : public LocalInterface {
virtual void some_func(Injector& i) {
i.inject();
}
};
In the interfaces looks like this.
class Injector {
virtual void inject() = 0;
};
class LocalInterface {
virtual void some_func(Injector& i) = 0;
};
Then I do the following:
class MyInjector : public Injector {
virtual void inject() {throw std::runtime_error("arrgghh");}
};
int main() {
LocalInterface* foreign_obj = create_object_from_my_dll();
MyInjector injector;
foreign_obj->some_func(injector);
destroy_object_from_my_dll(foreign_obj);
return 0;
}
My question is, why is it safe/not safe to throw an exception like this. Is it safe when they are built with the same compiler? Between compilers?
I would say the answer will depend on the OS. But for all the UNICES I’ve worked with (including Linux and Mac OS X), it will be safe. Of course, you need to compile with compilers using the same ABI, but the ABI of g++ hasn’t changed in years (can’t remember exactly, but I think 3.2 was the last big change). Also, in the model used in Linux, linkage don’t impact code behaviour. So you can safely put any code in a dynamically linked file (i.e. shared object file), it will work as if it is linked statically.
On Windows, if you use VC++, then you won’t be able to compile your library with another compiler. The program and the library must use the same version of VC++, there is no compatibility in either direction. If you are using g++, you can compile with another version of g++ (like on UNIX), but not with VC++. As for the question of it this is dangerous, I will let a windows-specialist answer as DLL have weird behaviour, and if I remember an object should always be destroyed within the scope of the DLL that loaded it, but I am not 100% sure.