简体   繁体   中英

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

How do I make the code below only call the move-constructor once ?

OUTPUT

MC
MC

CODE

#include <vector>
#include <map>
#include <memory>
#include <iostream>

struct Bar
{
        Bar() { }
        Bar( Bar&& rhs )
        {
                std::cerr << "MC\n";

                for( auto& p : rhs.m_v )
                {
                        std::cerr << "inside loop\n";
                        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 )));
}

EDIT

It looks like emplace is the right answer - but unfortunately, it's not in gcc 4.7.2 yet... ...is there some way I can alias this to insert and then remove it when it's properly implemented?

使用std::map::emplace

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

基本上通过使用emplace而不是insert

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM