每当需要字符串文字时,是否可以使用std :: string :: c_str()?

Get*_*ree 3 c++ casting c-strings string-literals rapidjson

我猜这个代码中的最后两行应该编译.

#include "rapidjson/document.h"

int main(){
    using namespace rapidjson ;
    using namespace std ;

    Document doc ;
    Value obj(kObjectType) ;
    obj.AddMember("key", "value", doc.GetAllocator()) ; //this compiles fine
    obj.AddMember("key", string("value").c_str(), doc.GetAllocator()) ; //this does not compile!
}
Run Code Online (Sandbox Code Playgroud)

不过,我的猜测是错误的.一行编译而另一行不编译.

AddMember方法有几个变体,如此处所述,但除此之外...为什么返回.c_str()不等同于字符串文字?

我的理解是,无论何时接受字符串文字,你都可以通过string::c_str(),它应该可以工作.

PS:我正在使用VC++ 2010进行编译.

编辑:
缺乏#include <string> 不是问题.它已被包括在内document.h

这是错误:

error C2664: 'rapidjson::GenericValue<Encoding> &rapidjson::GenericValue<Encoding>::AddMember(rapidjson::GenericValue<Encoding> &,rapidjson::GenericValue<Encoding> &,Allocator &)'
: cannot convert parameter 1 from 'const char [4]' to 'rapidjson::GenericValue<Encoding> &'
    with
    [
        Encoding=rapidjson::UTF8<>,
        Allocator=rapidjson::MemoryPoolAllocator<>
    ]
    and
    [
        Encoding=rapidjson::UTF8<>
    ]
Run Code Online (Sandbox Code Playgroud)

EDIT2:
请忽略在.c_str()时间值上调用的事实.此示例仅用于显示编译错误.实际代码使用字符串变量.


EDIT3:
代码的替代版本:

string str("value") ;
obj.AddMember("key", "value", doc.GetAllocator()) ; //compiles
obj.AddMember("key", str, doc.GetAllocator()) ; // does not compile
obj.AddMember("key", str.c_str(), doc.GetAllocator()) ; // does not compile
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 5

std::string::c_str()方法返回一个char const*.类型的字符串文字的是char const[N]其中N是字符的字符串中的数字(包括空终止).相应地,结果c_str()可以被用在所有的地方字符串文字,可以使用的地方!

如果您尝试调用的接口需要一个char数组,我会感到惊讶.也就是说,在你使用它应该工作.您更有可能需要包含<string>.

  • @JasonC:你不能把字符串文字传递给期待`char*`的东西!C语言11总是弃用并删除特殊转换的C向后兼容性. (3认同)