Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::string::c_str() be used whenever a string literal is expected?

I would guess that the last two lines in this code should compile.

#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!
}

My guess would be wrong, though. One line compiles and the other does not.

The AddMember method has several variants as documented here, but beyond that... why is the return of .c_str() not equivalent to a string literal?

My understanding was that where ever a string literal was accepted, you could pass string::c_str() and it should work.

PS: I'm compiling with VC++ 2010.

EDIT:
The lack of #include <string> is not the problem. It's already included by document.h

This is the error:

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:
Please ignore the fact that .c_str() is called on a temporal value. This example is just meant to show the compile error. The actual code uses a string variable.


EDIT3:
Alternate version of the code:

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
like image 1000
GetFree Avatar asked Dec 07 '22 20:12

GetFree


1 Answers

The std::string::c_str() method returns a char const*. The type of a string literal is char const[N] where N is the number of characters in the string (including the null terminator). Correspondingly, the result of c_str() can not be used in all places where a string literal can be used!

I'd be surprised if the interface you are trying to call requires a char array, though. That is, in your use it should work. It is more likely that you need to include <string>.

like image 126
Dietmar Kühl Avatar answered Dec 10 '22 09:12

Dietmar Kühl