cannot convert from 'std::string' to 'LPSTR'

前端 未结 6 2080
故里飘歌
故里飘歌 2020-12-09 16:12

As I clould not pass LPCSTR from one function to another (Data get changed) I tried passing it as a string.

But later I need to again convert it back to LPSTR. While

6条回答
  •  被撕碎了的回忆
    2020-12-09 17:07

    If you need an LPSTR, that means the string will/may be modified. std::string::c_str() returns a const pointer, and you can't just const_cast it away and hope all is good in the world, because it isn't. The string may be changed in all sorts of nasty ways, and your original std::string will be oblivious to all of them.

    Try this instead:

    // myFunction takes an LPSTR
    std::string cppString = "something";
    LPSTR cString = strdup( cppString.c_str() );
    try {
       myFunction( cString );
       cppString = cString;
    } catch(...) {
       free( cString );
    }
    

    Wrap the string in a smart pointer and get rid of the try...catch for bonus points (don't forget the custom deleter).

提交回复
热议问题