2017-04-02 2 views
3

클래스 cBar의 두 인스턴스를 emplace_back 함수가있는 벡터에 저장하려고합니다.emplace_back은 생성자를 이동하고 소멸자를 호출합니다.

reference에 따르면 emplace_back을 호출하면 벡터에서 자리를 예약하기 만 한 다음 "in place"라는 새 인스턴스를 만듭니다.

지금, 나는 그것으로 실험을 시도 :

#include <vector> 
#include <iostream> 
#include <memory> 
#include <string> 


class cBar 
{ 
public: 

    cBar(const int index); 
    cBar(cBar&& other); //needed for emplace_back? 
    ~cBar(); 

private: 
    cBar(const cBar& other) = delete; 
    cBar& operator=(const cBar& other) = delete; 

public: 
    int       mIndex; 

}; 




cBar::cBar(const int index) : mIndex(index) 
{ 
    std::cout << "cBar being created ..." << std::endl; 
} 
cBar::cBar(cBar&& other) : mIndex(other.mIndex) 
{ 
    std::cout << "cBar being moved ..." << std::endl; 
} 
cBar::~cBar() 
{ 
    std::cout << "cBar being destroyed ..." << std::endl; 
} 

int main() 
{ 
    std::vector<cBar> mBars; 

    std::cout << "Begin to create 2 cBar instance, I am expecting 2 \"cBar being created ...\" messages here" << std::endl; 
    mBars.emplace_back(0);//this supposed to call only cBar(const int index) constructor, and nothing more 
    mBars.emplace_back(1);//this works as expected, only one constructor call 

    //destroy all 
    std::cout << "Destroy the 2 isntances (this works, I see the two expected \"cBar being destroyed ...\" messages here" << std::endl; 
    mBars.clear(); 

    std::cin.get(); 
    return 0; 
} 

출력 :

Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here 
cBar being created ... 
cBar being moved ... 
cBar being destroyed ... 
cBar being created ... 
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here 
cBar being destroyed ... 
cBar being destroyed ... 

위를 실행하면, 첫 번째 emplace_back는 "현재 위치에서"인스턴스를 생성 것을 볼 수 있습니다 , 그런 다음 즉시 이동 생성자를 호출하면 소멸자가 호출됩니다.

두 번째 emplace의 경우 예상되는 동작을 봅니다. 하나의 생성자 만 호출합니다.

나는이 개 질문이 : 난 그냥 항목을 emplace_back하고와 push_back을 사용하지 않을하려면 내 수업 시간에 이동 생성자를 정의해야 할 이유

  1. .

  2. 첫 번째 인스턴스 생성의 경우 이동 생성자와 소멸자가 호출되는 이유는 무엇입니까? 첫 번째 인스턴스의 데이터에 액세스하면 모두 올바른 것으로 보이므로 이동 생성자 및 소멸자가 호출되는 이유를 알 수 없습니다.

나는 각 단계에서 비주얼 스튜디오를 벡터 크기가 2015

출력을 사용 하나

Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here 
Vector size:0 
cBar being created ... 
Vector size:1 
cBar being moved ... 
cBar being destroyed ... 
cBar being created ... 
Vector size:2 
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here 
cBar being destroyed ... 
cBar being destroyed ... 
+3

테스트 전에'mBars.reserve (9);'를 추가하십시오. –

답변

3

2. 첫 번째 인스턴스 생성의 경우 이동 생성자와 소멸자가 호출되는 이유는 무엇입니까?

emplace_back으로 두 번째 요소를 삽입하면 재 할당이 발생하기 때문에; vector의 내부 저장소를 확장해야하며 이전 저장소의 요소를 새 저장소로 복사/이동 한 다음 삭제해야합니다.

1. emplace_back 항목 만 사용하고 push_back을 사용하지 않으려면 왜 클래스에 이동 생성자를 정의해야합니까?

위의 설명과 같이, vector은 복사/이동 조작에 의해 요소를 이동시킬 필요가있다. 따라서 클래스의 복사 또는 이동 생성자를 정의해야합니다.emplace_backpush_back 모두에 해당합니다. 둘 다 vector에 요소를 추가하고 다시 할당 할 수 있기 때문입니다.

+1

자세한 답변, 고마워요! – Avithohol

1

확율이 벡터의 용량, 그리고 당신은 두 번째 요소를 넣을 때 , 벡터의 크기를 조정해야했습니다. 그것은 기억 속에서 움직이는 것들과 당신이 보는 증상으로 바뀔 수 있습니다.

Kerreks의 조언이 좋습니다. 각 작업의 전후에 벡터 용량을 인쇄하여 용량 변경이 원인인지 확인하는 것이 좋습니다.

+0

소원 나는 한 번에 두 개의 응답을 표시 할 수 있습니다. 도와 주셔서 감사합니다! 질문을 출력으로 편집했습니다. – Avithohol

관련 문제