两个相同的本地实例化模板能否跨越 DLL 边界?

时间:2021-05-13 04:49:05

标签: c++ dll template-meta-programming

我看到当 dll 公开的类包含 STL 容器作为其成员或函数参数时,编译器会发出警告,因为不能保证 STL 在各种编译器上生成相同的二进制文件。

然而,如果那些不安全性来自“实现并不总是相同的”,那么我们是否可以假设我们自己的模板类,从不依赖于 STL,可以安全地跨越 dll 边界?

就像我们有下面的模板类,

// my_vector.hxx
template<typename Ty>
class my_vector {
  // Some functions...
private:
  Ty_* _ptr; // Internally, contiguous memory will be allocated.
  size_t _size;
  size_t _capacity;
}

然后我们使用这两个不同的 dll,

// A.dll, A.cpp
extern "C" void* create_A() {
  return new my_vector<int>{}; // instantiates my_vector<int> locally.
}

// B.dll, B.cpp
extern "C" void use_B(void* pv) {
  (*(my_vector<int>*)pv).some_fn(); // instantiates my_vector<int> locally either.
}

然后一个可执行文件引用了两个 dll,

// foo.exe
void bar(){
  auto data = create_A(); // from A.dll
  use_B(data);           // into B.dll
}

那么我们可以假设上面的例子在一般用例中正常工作吗?与多个 DLL 之间的 STL 使用不同?

0 个答案:

没有答案
相关问题