Is it safe to pass std::string to C style APIs?

后端 未结 5 705
南笙
南笙 2021-01-04 23:16

It is well defined C++ to pass std::vector to C APIs that expect an output array like so because std::vector is contiguous:

std::vector myArray(a         


        
5条回答
  •  时光取名叫无心
    2021-01-05 00:07

    If the C API function requires read-only access to the contents of the std::string then use the std::string::c_str() member function to pass the string. This is guaranteed to be a null terminated string.

    If you intend to use the std::string as an out parameter, C++03 doesn't guarantee that the stored string is contiguous in memory, but C++11 does. With the latter it is OK to modify the string via operator[] as long as you don't modify the terminating NULL character.

提交回复
热议问题