英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论