Converting a void* to a std::string

后端 未结 4 2010
深忆病人
深忆病人 2020-12-29 20:32

After perusing the web and messing around myself, I can\'t seem to convert a void*\'s target (which is a string) to a std::string. I\'ve tried using sprintf(buffer, \"

4条回答
  •  孤城傲影
    2020-12-29 21:08

    Based on your comment "What I meant was to convert what the void* is pointing to (which is a string) into a string."

    Assuming you have this:

    std::string str = ...;
    void *ptr = &str;
    

    You can just cast back to the string:

    std::string *pstr = static_cast(ptr);
    

    Note that it is on you to verify that ptr actually points to a std::string. If you are mistaken and it points to something else, this will cause undefined behavior.

提交回复
热议问题