このコードの最後の2行がコンパイルされるはずです。文字列リテラルが必要なときはいつでも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!
}
私の推測は間違っています。 1行はコンパイルされ、もう1行はコンパイルされません。
hereのように、AddMember
メソッドにはいくつかのバリエーションがありますが、それ以外の理由は... .c_str()
が文字列リテラルに相当しないのはなぜですか?
私は文字列リテラルが受け入れられたところで、string::c_str()
を渡すことができました。
PS:
#include <string>
の欠如が問題ではありません:私はVC++ 2010
EDITしてコンパイルしています。 .c_str()
は時間的価値に呼ばれているという事実を無視してください
:
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:それはすでにdocument.h
によってこのエラーであるが含まれています。この例はコンパイルエラーを表示するためのものです。実際のコードは文字列変数を使用します。
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