弱链接的实际应用是什么?
使用特殊的编译器命令可以声明一个符号weak.根据维基百科:
Using special compiler commands a symbol can be declared weak. According to Wikipedia:
弱符号是目标文件或动态库中可能被其他符号定义覆盖的符号定义
a weak symbol is a symbol definition in an object file or dynamic library that may be overridden by other symbol definitions
在哪些场景或哪些应用中需要弱符号?有哪些典型用例?
In what scenarios or for what applications do you need weak symbols? What are typical use cases?
推荐答案
弱链接的一个用途是在 C++ 标准中实现 可替换 函数.即:
One use of weak linking is implementing the replaceable functions in the C++ standard. Namely:
void *operator new(std::size_t);
void *operator new(std::size_t, std::nothrow_t const &) noexcept;
void *operator new[](std::size_t);
void *operator new[](std::size_t, const std::nothrow_t&) noexcept;
void operator delete(void *) noexcept;
void operator delete(void *, std::nothrow_t const &) noexcept;
void operator delete[](void *) noexcept;
void operator delete[](void *, std::nothrow_t const &) noexcept;
这些是实现必须提供的功能,但如果程序实现了它们,那么程序的实现将替换或覆盖实现的版本.这很容易通过弱链接实现.
These are functions which must be provided by the implementation, but if a program implements them then the program's implementation replaces or overrides the implementation's version. This is easily implemented via weak linkage.
相关文章