我想这个代码中的最后两行应该编译。每当预期字符串文字时,可以使用std :: string :: c_str()吗?
#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!
}
虽然我的猜测是错误的。一行编译,另一行不行。
AddMember
方法有几个变种,如文档here,但除此之外......为什么.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<>
]
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
您是否包含''?而且,'main()'总是返回'int'。 –
字符串文字具有数组类型,而'c_str()'返回一个指针。有可能会有功能超载,可以说明差异(但相当不友好,使他们的行为显着不同)。 –
'string(“value”).c_str()'的生存期非常有限。所以除非'const char *'的副本完成,否则你可能有悬挂指针。 – Jarod42