Search code examples
c++stringinline-code

How many temporary objects are created when I return a string from an inline function?


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?


Solution

  • As the following code is initializing a and not assigning to it

    std::string a = T.getCString(0);
    

    is equivalent to

    std::string a(T.getCString(0)); // Construct "a" with return value of function.
    

    or

    std::string a(std::string(queryQt->value(0).toString().toStdString()));
    

    This means there will be a copy construction of std::string when returning from the function and another copy construction when constructing a 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 both std::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 in a, 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