用于澄清代码边界的大括号范围是否会增加代码执行时间?在我看来,确实如此.因为在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"; }