0

I want to assign the value in QString to a const std::string

QString qfile("some value");

this is the const std::string variable

const std::string file

The code that I m using

file = qfile.toStdString();

above codes works fine for a normal std::string . But there is some problem because of the keyword 'const'. How do I solve it ?

Vihaan Verma
  • 12,815
  • 19
  • 97
  • 126
  • 3
    Any work around? Yes: if you want to change something, don't declare it `const`. Or, if you want it to be immutable, then don't try to change it. – Mike Seymour Jun 27 '12 at 12:28
  • Possibly a const_cast but what is the logic that requires you to assign to a const variable? Perhaps you should update that rather than applying a work around? – Stefan Jun 27 '12 at 12:28
  • 2
    @Stefan: `const_cast` would make it compile, but trying to modify a `const` object gives undefined behaviour. – Mike Seymour Jun 27 '12 at 12:29
  • note that `Qt::toStdString()` by default converts the string to Latin1 encoding, and because of that any characters which cant be represented in Latin1 will be lost. If you use that `std::string` for filenames, you wont be able to handle files with names containing special characters. You can use `const std::string file = qFile.toUtf8().constData();` intstead. But on Windows you wont be able to use the `std::string` for file operations anyway, because Windows does not support UTF8 properly. – smerlin Jun 27 '12 at 12:36
  • 1
    @VihaanVerma: Why did you declare it `const` in the first place ? We really need to know that. – ereOn Jun 27 '12 at 12:37

3 Answers3

7

Don't use the assignment operator to initialize the std::string object but rather initialize the variable directly.

const std::string file = qfile.toStdString();

That aside, please make sure that you're aware of what encoding QString::toStdString() uses; unlike QString, std::string is encoding-agnostic (it's a string of bytes, not characters).

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
1

Constants are expressions with a fixed value.

http://www.cplusplus.com/doc/tutorial/constants/

Jake1164
  • 12,291
  • 6
  • 47
  • 64
0

You can also get rid of the const by making copy of the return value of toStdString():

QString str("text");
std::string std_str(str.toStdString());
weggo
  • 134
  • 3
  • 10