Consider the following code:
QSqlQuery *queryQt; // represents a row in a database table
inline std::string getCString(size_t col) {
return queryQt->value(col).toString().toStdString();
}
where queryQt->value(col).toString()
represents a string value of a specific column of the row in the database.
Let us assume that the compiler has all the optimizations on.
Question: is the following code:
std::string a = T.getCString(0);
equivelent to
std::string a = queryQt->value(col).toString().toStdString();
or to
std::string temp = queryQt->value(col).toString().toStdString();
std::string a = temp;
?
Question Update:
does it make a difference, if I add const to the return type?
As the following code is initializing
a
and not assigning to itis equivalent to
or
This means there will be a copy construction of
std::string
when returning from the function and another copy construction when constructinga
from the return value. So 2 copies.However on C++11 compilers, move construction will be used instead when constructing the return value and
a
as bothstd::string
objects constructed from is temporaries. This means that there will be only 2 moves instead of 2 copies.And finally because of copy elision optimizations the compiler will most likely elide the copies all together and simply construct the
std::string
directly ina
, resulting in no copies at all.Inlining the function have no relevance on the number of copies being made. Changing the return type to
const
will prevent move construction as you cant move from a const object.Look at this live example using my noisy class