클래스 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을 사용하지 않을하려면 내 수업 시간에 이동 생성자를 정의해야 할 이유
.
첫 번째 인스턴스 생성의 경우 이동 생성자와 소멸자가 호출되는 이유는 무엇입니까? 첫 번째 인스턴스의 데이터에 액세스하면 모두 올바른 것으로 보이므로 이동 생성자 및 소멸자가 호출되는 이유를 알 수 없습니다.
나는 각 단계에서 비주얼 스튜디오를 벡터 크기가 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 ...
테스트 전에'mBars.reserve (9);'를 추가하십시오. –