次のような複雑なオブジェクトを返す関数があるとしますstd::string。
std::string find_path(const std::string& filename);
そのメソッドを呼び出した結果を に保存する価値はありconst auto&ますか?
void do_sth() {
//...
const auto& path = find_path(filename);
//...
}
そのようなアプローチは、オブジェクトのコピー/移動を防ぎます。それでいいです。しかし一方で、auto代入の左辺を統一するために導入されました。Herb Sutter は、CppCon2014 のプレゼンテーションで、C++ の左から右へのモダンなスタイルについて言及しています https://www.youtube.com/watch?v=xnqTKD8uD64 (39:00-45:00)。
C++98 ではstd::stringat const ref を保存しても問題ありませんでした。C++11 ではどうですか?
更新 (2016-07-27 2:10 GMT+0):
申し訳ありませんが、私の質問は正確ではありませんでした。私はコーディングスタイルを意味しました - 追加するのが良いですか、const &それとも単にそのままにしautoて、コンパイラがやりたいことを何でもできるようにするのが良いですか.
更新された例:
unsigned int getTimout() { /* ... */ }
int getDepth() { /* ... */ }
std::string find_path(const std::string& filename,
unsigned int timeout,
int depth) { /* ... */ }
void open(const std::string& path) { /* ... */ }
2 つのアプローチ:
void do_sth() {
//...
auto timeout = getTimeout();
auto depth = getDepth();
const auto& path = find_path(filename, timeout, depth);
open(path)
//...
}
対
void do_sth() {
//...
auto timeout = getTimeout();
auto depth = getDepth();
auto path = find_path(filename, timeout, depth);
open(path);
//...
}
質問: 私たちは
const auto&複雑な戻りオブジェクトとautoプリミティブを格納するために使用する、またはautoHerb がプレゼンテーション (上記のリンク) で言及した、左から右への最新の C++ スタイルを維持するために、すべてに使用します。