用于澄清代码边界的大括号范围是否会增加代码执行时间?在我看来,确实如此.因为在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";
}
Run Code Online (Sandbox Code Playgroud)
退出作用域会破坏该作用域中声明的所有局部变量(最年轻的首先)。在您的示例中,作用域中没有声明局部变量,因此应该没有开销。在这种情况下,您可以通过编译为汇编语言(-s在 gcc 下)(带或不带大括号)并比较结果来确认这一点。
| 归档时间: |
|
| 查看次数: |
481 次 |
| 最近记录: |