Vector :: push_back and std :: move

I tried the following code:

#include <iostream>

struct test{
    test(){}
    test(test const &){
        std::cout<<__LINE__<<"\n";
    }
    test(test&&){
        std::cout<<__LINE__<<"\n";
    }
};

#include <vector>
#include <utility> // std::move
int main(){
    auto&& tmp = test();
    std::vector<test> v;
    v.push_back(tmp);
    std::cout<<__LINE__<<"\n";
    v.push_back(std::move(tmp));

    return 0;
}

Vs2013 compiler output:

6 // copy

eighteen

9 // move

9 // move

The result of g ++ and clang ++:

6 // copy

eighteen

9 // move

6 // copy

My problems:

  • Is type tmp test &? Is tmp a r value?

  • If the tmp type is test & &, why didn't the first move_back constructor use the move constructor?

  • Where did the last exit come from? Why vs2013 and g ++ give different results?

Thank.

Answer for the third problem: This comes from redistribution, as commented by andrew.punnett.

+3
source share
2 answers

tmp test&&What is the type ?

. tmp rvalue test&&, tmp, , test lvalue. & .

tmp r

. - lvalue, rvalue. Rvalue lvalue; decltype(tmp) . ( decltype((tmp)), .)

tmp test & &, move_back ?

rvalue lvalue. rvalue, move(tmp).

? vs2013 g++ ?

Clang GCC vector. , , . ? noexcept, , , .

MSVC, , - .

  • MSVC . - .
  • MSVC , noexcept . , .

vector deque, , deque .

+4

Visual Studio noexcept , , push_back. , .

#include <iostream>
#include <vector>
#include <utility> // std::move

struct Except{
    Except(){}
    Except(Except const &) {
        std::cout<< "COPY\n";
    }
    Except(Except&&)  {
        std::cout<< "MOVE\n";
    }
};

struct NoExcept{
    NoExcept(){}
    NoExcept(NoExcept const &) noexcept {
        std::cout<< "COPY\n";
    }
    NoExcept(NoExcept&&) noexcept {
        std::cout<< "MOVE\n";
    }
};

template <typename T> void Test( char const *title,int reserve = 0) {
    auto&& tmp = T();
    std::cout<< title <<"\n";
    std::vector<T> v;
    v.reserve(reserve);

    std::cout<< "LVALUE REF ";
    v.push_back(tmp);
    std::cout<< "RVALUE REF ";
    v.push_back(std::move(tmp));
    std::cout<< "---\n\n";
}
int main(){
    Test<Except>( "Except class without reserve" );
    Test<Except>( "Except class with reserve", 10 );
    Test<NoExcept>( "NoExcept class without reserve" );
    Test<NoExcept>( "NoExcept class with reserve", 10 );
}

clang:

Except class without reserve
LVALUE REF COPY
RVALUE REF MOVE
COPY
---

Except class with reserve
LVALUE REF COPY
RVALUE REF MOVE
---

NoExcept class without reserve
LVALUE REF COPY
RVALUE REF MOVE
MOVE
---

NoExcept class with reserve
LVALUE REF COPY
RVALUE REF MOVE
---
+2

All Articles