Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update item42.md #193

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/8.Tweaks/item42.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ vs.push_back(std::string("xyzzy")); //创建临时std::string,把它传给push
为了在`std::string`容器中创建新元素,调用了`std::string`的构造函数,但是这份代码并不仅调用了一次构造函数,而是调用了两次,而且还调用了`std::string`析构函数。下面是在`push_back`运行时发生了什么:

1. 一个`std::string`的临时对象从字面量“`xyzzy`”被创建。这个对象没有名字,我们可以称为`temp`。`temp`的构造是第一次`std::string`构造。因为是临时变量,所以`temp`是右值。
2. `temp`被传递给`push_back`的右值重载函数,绑定到右值引用形参`x`。在`std::vector`的内存中一个`x`的副本被创建。这次构造——也是第二次构造——在`std::vector`内部真正创建一个对象。(`x`副本拷贝到`std::vector`内部的构造函数是移动构造函数,因为`x`在它被拷贝前被转换为一个右值,成为右值引用。有关将右值引用形参强制转换为右值的信息,请参见[Item25](../5.RRefMovSemPerfForw/item25.md))。
2. `temp`被传递给`push_back`的右值重载函数,绑定到右值引用形参`x`。在`std::vector`的内存中一个`x`的形参被创建。这次构造——也是第二次构造——在`std::vector`内部真正创建一个对象。(构造`x`使用的是移动构造函数,因为`x`在它被拷贝前被转换为一个右值,成为右值引用。有关将右值引用形参强制转换为右值的信息,请参见[Item25](../5.RRefMovSemPerfForw/item25.md))。
3. 在`push_back`返回之后,`temp`立刻被销毁,调用了一次`std::string`的析构函数。

对于性能执着的人不禁注意到是否存在一种方法可以获取字符串字面量并将其直接传入到步骤2里在`std::vector`内构造`std::string`的代码中,可以避免临时对象`temp`的创建与销毁。这样的效率最好,对于性能执着的人也不会有什么意见了。
Expand Down
Loading