Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to return string in C++?

Tags:

c++

string

My question is simple: if I have some class Man and I want to define member function that returns man's name, which of the following two variants shall I prefer?

First:

string name(); 

Second:

void name(/* OUT */ string &name); 

The first variant is kind of inefficient because it makes unnecessary copies (local variable -> return value -> variable in the left part of assignment).

The second variant looks pretty efficient but it makes me cry to write

string name; john.name(name); 

instead of simple

string name(john.name()); 

So, what variant shall I prefer and what is the proper trade-off between efficiency and convenience/readability?

Thanks in advance.

like image 257
tonytony Avatar asked May 11 '12 14:05

tonytony


People also ask

Can you return a string literal in C?

You can safely return C strings from a function in at least these ways: const char* to a string literal. It can't be modified and must not be freed by caller.

Which function returns a string within a string?

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string.

How do I return a char?

If you want to return a char* from a function, make sure you malloc() it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior. Voting is disabled while the site is in read-only mode.


2 Answers

It's a good question and the fact that you're asking it shows that you're paying attention to your code. However, the good news is that in this particular case, there's an easy way out.

The first, clean method is the correct way of doing it. The compiler will eliminate unnecessary copies, in most cases (usually where it makes sense).

EDIT (6/25/2016)

Unfortunately it seems that David Abaraham's site has been offline for a few years now and that article has been lost to the ethers (no archive.org copy available). I have taken the liberty of uploading my local copy as a PDF for archival purposes, and it can be found here.

like image 142
Mahmoud Al-Qudsi Avatar answered Oct 14 '22 19:10

Mahmoud Al-Qudsi


use the first variant:

string name(); 

The compiler will most likely optimize out any unnecessary copies. See return value optimization.

In C++11, move semantics means that you don't perform a full copy even if the compiler doesn't perform RVO. See move semantics.

Also bear in mind that if the alternative is

void name(std::string& s); 

then you have to specify very clearly what can happen to s and what values it can have when passed to the function, and probably either do a lot of validity checking, or simply overwrite the input entirely.

like image 28
juanchopanza Avatar answered Oct 14 '22 18:10

juanchopanza