什么是 multimap::emplace() 和 move()?
我正在查看有关 multimap 的 MSDN 文档,发现它有一个成员函数 multimap::emplace()。下面是该成员函数的示例。
int main( ) {
using namespace std;
multimap<int, string> m1;
pair<int, string> is1(1, "a");
m1.emplace(move(is1));
}
看来 emplace()
和 move()
是 C++0x。有人能为我解释一下吗?我读过有关 move()
的内容,但我真的不明白它的作用(在幕后)。
I was viewing the MSDN doc about multimap and find that it has a member function multimap::emplace(). Below is the example of that member function.
int main( ) {
using namespace std;
multimap<int, string> m1;
pair<int, string> is1(1, "a");
m1.emplace(move(is1));
}
It seems that emplace()
and move()
are C++0x. Can someone explain them for me? I read about move()
, but I really don't understand what does it do (under the hood).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用向量来放置更容易理解。
my_vector.emplace_back(1, 2, 3)
基本上是my_vector.push_back(some_type(1, 2, 3))
的有效快捷方式。现在可以使用任何构造函数进行就地构造,而不是就地复制构造对象,从而节省了临时对象的创建、复制(或移动)和销毁。 Emplacecing 由完美转发提供支持。std::move(expression)
基本上是对 xvalue 的强制转换,它有效地允许整个要绑定到右值引用的表达式。您通常这样做是为了从您不再感兴趣的命名对象中窃取资源,因为无论如何它们很快就会被销毁。Emplacing is easier to understand with vectors.
my_vector.emplace_back(1, 2, 3)
is basically an efficient shortcut formy_vector.push_back(some_type(1, 2, 3))
. Instead of copy-constructing the object in-place, any constructor can now be used for in-place-construction, thus saving the creation, copy (or move) and destruction of a temporary object. Emplacing is powered by perfect forwarding.std::move(expression)
is basically a cast to an xvalue, which effectively allows the entire expression to be bound to an rvalue reference. You typically do this to enable resource pilfering from named objects that you are no longer interested in because they are going to be destroyed soon, anyway.