假设我有一个这样定义的抽象基类:
接口.hpp
#ifndef INTERFACE_HPP
#define INTERFACE_HPP 1
class interface{
public:
virtual void func() = 0;
};
#endif // INTERFACE_HPP
然后我将一个翻译单元编译test.cpp
成一个共享对象test.so
:
测试.cpp
#include "interface.hpp"
#include <iostream>
class test_interface: public interface{
public:
void func(){std::cout << "test_interface::func() called\n";}
};
extern "C"
interface &get_interface(){
static test_interface test;
return test;
}
如果我在可执行文件中打开该共享对象并尝试get_interface
像这样调用:
#include <dlfcn.h>
#include "interface.hpp"
int main(){
void *handle = dlopen("test.so", RTLD_LAZY);
void *func = dlsym(handle, "get_interface");
interface &i = reinterpret_cast<interface &(*)()>(func)();
i.func(); // print "test_interface::func() called"
dlclose(handle);
}
(假装我做了错误检查)
行为是否明确定义?还是我假设这将永远有效,从而踩到自己的脚趾?
请记住,我只会使用 clang 和 gcc