Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to send QStrings in a function call?

Tags:

I would like to know what is the most efficient and practical way of sending a Qstring as a parameter to a function, in QT more specifically. I want to use a reference. The problem is I also want to instantiate that string in the function itself like so for example:

this is the function prototype:

void myFunction(QString & theMsg); 

this is the function call:

myFunction(tr("Hello StringWorld")); 

now the function tr() returns a QString but it doesn't work with a reference(I can see why).

I have to do this:

QString theQstr("Hello StringWorld");  myFunction(theQstr); 

Is there a simpler way to do this while still using references or could I just change the function parameter to use a QString and it would still be efficient?

like image 334
yan bellavance Avatar asked Jan 20 '10 19:01

yan bellavance


People also ask

How do you create a QString?

One way to initialize a QString is simply to pass a const char * to its constructor. For example, the following code creates a QString of size 5 containing the data "Hello": QString str = "Hello"; QString converts the const char * data into Unicode using the fromAscii() function.

How do you split a QString?

To break up a string into a string list, we used the QString::split() function. The argument to split can be a single character, a string, or a QRegExp. To concatenate all the strings in a string list into a single string (with an optional separator), we used the join() function.

How do you convert QString to string?

You can use: QString qs; // do things std::cout << qs. toStdString() << std::endl; It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well.


1 Answers

QString uses COW (Copy On Write) behind the scenes, so the actual string isn't copied even if you use a signature like this:

void myFunction(QString theMsg)

(until you modify it that is).

If you absolutely want a reference I would use a const& unless you plan to modify the input argument.

void myFunction(QString const& theMsg)

like image 81
Morten Fjeldstad Avatar answered Sep 30 '22 21:09

Morten Fjeldstad