使用 `const char*` 而不是 `const string`

huangapple go评论71阅读模式
英文:

Using const char* instead of const string

问题

我浏览了 LLVM 源代码,并找到了以下函数声明。

int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path){...}

(在 https://github.com/llvm/llvm-project/blob/main/llvm/lib/Bitcode/Writer/BitWriter.cpp

我们为什么要使用 const char* 而不是 const string?是否有与性能相关的原因?

英文:

I was going through llvm source code and found the following function declaration.

int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path){...}

(at https://github.com/llvm/llvm-project/blob/main/llvm/lib/Bitcode/Writer/BitWriter.cpp)

Is there a reason to use const char* when we can instead use const string? Any performance-related reasons?

答案1

得分: 3

通常在具有共享的C和C++代码的项目中,以及在从其他语言使用的库和有时在纯C++项目之间,人们会避免在接口边界上使用非平凡的C++类(特别是那些分配内存的类,比如std::string)。这 a) 方便了C绑定, b) 防止ABI不兼容问题,例如当调用方使用不同的标准库版本或不同的malloc实现时,而被调用的函数是使用不同版本编译的。

在LLVM的情况下,原因可能是他们希望使C代码能够调用他们的接口。

在这里,您可以找到声明相关函数的C头文件:
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm-c/BitWriter.h

英文:

Generally in projects with shared C and C++ code, in libraries which are used from other languages and sometimes also between pure C++ projects, people refrain from using non-trivial C++ classes (especially ones that allocate memory such as std::string) on interface boundaries.

This a) allows easy C-bindings and b) prevents ABI-incompatibility issues, e.g. when the caller is using a different standard library version or a different malloc implementation than what the called function was compiled with.

In the case of LLVM the reason is probably that they want to enable C code to call their interfaces.

Here you can find the C-header declaring the function in question:
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm-c/BitWriter.h

huangapple
  • 本文由 发表于 2023年2月27日 00:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定