简体   繁体   中英

Can you construct a string from `volatile const char*` ? (without using `const_cast`)

Basicly I have volatile const char* and want to create a string . The volatile keyword here is in all likelyhood irrelevant(a misunderstanding from a previous dev), but cannot easily get rid of it (coming from other library).

cannot convert argument N from 'volatile const char *' to 'std::string

I could just use a const_cast to cast the volatile away (and making the compiler disregard volatile / const ). Im interested in a solution not using const_cast .

Do other methods exist, eg. could using a stringstream perhaps be a solution?

You can use the STL algorithm std::transform() to do an element-wise copy of your C string.

The transform function will effectively convert each volatile const char to a char -- a conversion that works without const_cast . Using std::back_inserter() , you can append the resulting characters to the end of your std::string .

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    volatile const char* cstr = "hello";
    std::size_t len = 6; // your string's length

    // this implicitly converts 'volatile const char' argument to 'char' parameter
    auto func = [] (char c) { return c; };
    std::string str;
    std::transform(cstr, cstr + len, std::back_inserter(str), func);

    std::cout << "string=" << str << ".\n"; // outputs:  string=hello.
}

Note that you cannot use std::strlen() for the same reason -- if you don't have the size, you need to write your own loop to calculate it.

Just using a for loop, may be an option:

volatile const char* cstr = "hello world";
std::string str;
for (volatile const char* pC = *cstr ; *pC != 0; ++pC) {
    str.push_back(*pC);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM