gpt4 book ai didi

c++ - 是否可以使用外部链接重载函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:31 25 4
gpt4 key购买 nike

我在 std::atexit 的声明中看到一个奇怪的代码:

extern "C"   int atexit( void (*func)() );
extern "C++" int atexit( void (*func)() ); // ... why are there two functions?

我猜这是某种函数重载,但看起来显然是错误的。

这是什么?为什么有必要?

最佳答案

你的来源有问题

这是 cppreference 有点误导。

用不同的storage-class-specifiers 声明同一个函数两次是非法的,causes a build failure .如果您查看 libstdc++(GCC 的标准库实现)的源代码,您会看到 only the extern "C" version is actually provided .


标准对此的看法

尽管[C++11: 18.5]列出两个声明,就像 cppreference 一样,这意味着两者都可以在单个实现中使用;这意味着一个实现可以选择声明它们中的任一个:也就是说,它占[C++11: 17.6.4.3.3/4]其中说:

Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage [..]

还有:

[C++11: 17.6.2.3/2]: Whether a name from the C standard library declared with external linkage has extern "C" or extern "C++" linkage is implementation-defined. It is recommended that an implementation use extern "C++" linkage for this purpose

此处规则明确:

[C++11: 7.5/5]: If two declarations declare functions with the same name and parameter-type-list (8.3.5) to be members of the same namespace or declare objects with the same name to be members of the same namespace and the declarations give the names different language linkages, the program is ill-formed; no diagnostic is required if the declarations appear in different translation units. [..]


为什么这会令人困惑

在我看来,这确实会在标准的其他地方引起一些问题;例如:

[C++11: 25.5/2]: The contents are the same as the Standard C library header <stdlib.h> with the following exceptions:

[C++11: 25.5/3]: The function signature:

bsearch(const void *, const void *, size_t, size_t,
int (*)(const void *, const void *));

is replaced by the two declarations:

extern "C" void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));

extern "C++" void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));

both of which have the same behavior as the original declaration.

I consider that to be a language defect.

关于c++ - 是否可以使用外部链接重载函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26160465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com