在C ++中返回字符串的最好方法是什么? [英] What is the best way to return string in C++?

查看:153
本文介绍了在C ++中返回字符串的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单:如果我有一个类Man,并且我想定义返回man的名字的成员函数,我应该选择以下两个变体:

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?

第一个:

string name();

其次:

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);

而不是简单

string name(john.name());

那么,我应该选择什么样的变体,什么是效率和方便性/可读性之间的权衡?

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

提前感谢。

推荐答案

事实上,你要求它显示你注意你的代码。但是,好消息是,在这种特殊情况下,有一个简单的方法。

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)

EDIT (6/25/2016)

似乎David Abaraham的网站已经离线了几年了,那篇文章已经失去了醚(没有archive.org的副本可用)。我已经自由地将我的本地副本作为PDF存档,并且

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.

这篇关于在C ++中返回字符串的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆