这是我的 C++ 代码中的一个片段:
std::queue<std::string> get_file_names(const std::string &indir)
{
std::queue<std::string> file_names;
fs::recursive_directory_iterator end;
for (fs::recursive_directory_iterator it(indir); it != end; it++) {
const std::string &extn = it->path().extension().string();
if (extn == ".zip") {
const std::string &file_name = it->path().string();
file_names.push(file_name);
}
}
return file_names;
}
使每个字符串都不会修改 const 引用是一个好习惯吗?我无法理解在这种情况下如何存在这样的引用。像it->path().string()
的返回值以上。当推回 vector 时,如何将其分配给以后可以在函数范围之外使用的引用?我觉得它必须用
std::move
做些什么.
最佳答案
您的代码:
const std::string &file_name = it->path().string();
延长临时文件的生命周期 std::string
返回者 std::filesystem::path::string()
.由于您已将其标记为 const
,不能移入file_names
,必须复制。假设你想要移动,你会写:auto&& file_name = // ...
file_names.push(std::move(file_name));
请注意 std::queue
有一个 push()
r 值引用的重载。现代 C++ 为编译器提供了很多优化机会,因此避免有关悬空引用的问题/“混淆”(
auto&&
语法在 C++11 中是“新的”)可能是更好的方法:auto file_name = // ...
file_names.push(std::move(file_name));
编写“看起来和行为都像 int
s”的“自然”代码通常是一个好方法。在不太可能的情况下你发现这确实是一个性能瓶颈,你可以重新审视;首先为了清晰起见编写代码。
关于C++:将字符串作为常量引用是否经常被认为是一种好习惯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66932946/