Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 497
darune Avatar asked Sep 21 '25 07:09

darune


2 Answers

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);
}
like image 186
darune Avatar answered Sep 22 '25 20:09

darune


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.

like image 33
TheOperator Avatar answered Sep 22 '25 20:09

TheOperator