假设我们有一个返回复杂对象的函数,例如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::string
at 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) { /* ... */ }
两种方法:
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
原语,或 - 使用
auto
一切来保持 Herb 在他的演示文稿中提到的从左到右的现代 C++ 风格(上面的链接)。