花括号作用域是否会增加代码执行时间? 在我看来,的确会。因为在C++中退出花括号作用域意味着堆栈展开,而为注释而使用花括号作用域会增加堆栈展开次数。但我不知道这是否昂贵?我能忽略这个副作用吗?
对于以下代码片段,您应该关注代码结构而不是代码本身。
#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
std::string str = "Hello";
std::vector<std::string> v;
{// uses the push_back(const T&) overload, which means
// we'll incur the cost of copying str
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
//other code involves local variable
}
{// uses the rvalue reference push_back(T&&) overload,
// which means no strings will be copied; instead, the contents
// of str will be moved into the vector. This is less
// expensive, but also means str might now be empty.
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
//other code involves local variable
}
std::cout << "The contents of the vector are \"" << v[0]
<< "\", \"" << v[1] << "\"\n";
}
-O0
,GCC输出的指令数量似乎与是否使用作用域保护一样(我没有检查它们是否是相同的指令,但我期望是);在-O3
下,如果它不能优化掉,我会感到震惊。 - Daniel H