gpt4 book ai didi

c++ - 将 std::string 传递给 C 风格的 API 是否安全?

转载 作者:可可西里 更新时间:2023-11-01 16:30:12 25 4
gpt4 key购买 nike

将 std::vector 传递给期望输出数组的 C API 是 C++ 定义良好的,因为 std::vector 是连续的:

std::vector<char> myArray(arraySize);
cStyleAPI(&myArray[0], arraySize);

以相同的方式将 std::string 传递给 C API 是否安全?标准 C++03 是否保证 std::string 是连续的并且在这种情况下以与 std::vector 相同的方式工作?

最佳答案

如果 C API 函数需要对 std::string 的内容进行只读访问,则使用 std::string::c_str() 成员函数传递字符串。这保证是一个空终止字符串。

如果您打算使用 std::string 作为 out 参数,C++03 不保证存储的字符串在内存中是连续的,但是C++11 可以。对于后者,只要您 don't modify the terminating NUL character 就可以通过 operator[] 修改字符串。 .

关于c++ - 将 std::string 传递给 C 风格的 API 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16425338/

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