如何只对move构造函数进行一次调用?

How do I make only a single call to the move-constructor?

本文关键字:一次 调用 move 构造函数      更新时间:2023-10-16

我如何使下面的代码只调用移动构造函数一次?

MC
MC

#include <vector>
#include <map>
#include <memory>
#include <iostream>
struct Bar
{
        Bar() { }
        Bar( Bar&& rhs )
        {
                std::cerr << "MCn";
                for( auto& p : rhs.m_v )
                {
                        std::cerr << "inside loopn";
                        m_v.push_back( move( p ));
                }
        }
        std::vector< std::unique_ptr< Bar >>  m_v;
};
int main()
{
        Bar b;
        std::map<int,Bar> m;
        m.insert( std::make_pair( 1, std::move( b )));
}

编辑

看起来emplace是正确的答案-但不幸的是,它还没有在gcc 4.7.2 ... ...有没有办法我可以把它混叠到insert然后在它正确实现的时候把它去掉?

使用std::map::emplace:

m.emplace(1, std::move(b));

实质上是用emplace代替insert:

m.emplace(1, std::move(b));