0

What is the reason for the choice of API below:

QString QString::fromStdString(const std::string & str) [static]

Why is there a need for calling a static function when we could have a constructor as follows:

QString::QString(const std::string & str)

There are similar constructors for the c string representation (char*), std::string being the exception. What is the reason for that?

4
  • 3
    I'd actually avoid QString(const char*) and use QLatin1String/QStringLiteral or QString::fromLatin1/QString::FromUtf8 etc. instead, for consciously and explicitly specifying the encoding used for conversion. Commented Apr 5, 2014 at 16:25
  • Noted! These calls also happen follow the static function pattern... Commented Apr 5, 2014 at 17:29
  • I believe this is the factory method pattern at work here... But I don't see they benefit of making an exception for coming strings? Commented Apr 5, 2014 at 17:35
  • An alternative could be having the constructor being explicit. Commented Apr 5, 2014 at 17:37

1 Answer 1

2

Qt predates explicit constructors, and it can't break its existing clients gratuitously. One other reason would be that std::string and QString are not necessarily in the same encoding/codepage and the static methods make explicit that some more expensive conversion is happening.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.