나는 코드의 follwing을 블록을 가지고 :왜 STL 벡터는 할당시 기본 생성자를 호출합니까?
#include <vector>
#include <iostream>
struct TestStruct {
bool wasCreated;
TestStruct() {
std::cout << "Default Constructor" << std::endl;
wasCreated = false;
}
~TestStruct() {
if (wasCreated) {
DoImportantStuff();
}
}
void Create() {
wasCreated = true;
}
// delete all copy stuff
TestStruct(const TestStruct&) = delete;
TestStruct& operator=(const TestStruct&) = delete;
// implement only move assignment & ctor
TestStruct(TestStruct&& other) {
std::swap(wasCreated, other.wasCreated);
}
TestStruct& operator=(TestStruct&& other) {
std::swap(wasCreated, other.wasCreated);
return *this;
}
// very important stuff
void DoImportantStuff() {
std::cout << "Do Important Stuff" << std::endl;
}
};
int main() {
std::vector<TestStruct> testVector;
testVector.emplace_back(TestStruct());
testVector.emplace_back(TestStruct());
std::cin.get();
}
이 코드는 출력에 이르게 :
기본 생성자
중요 물건
기본 생성자
할 일을 수행 중요 항목
중요 물건
가 Basicly 내가 메모리를 소유하지만 Create()
를 호출 할 경우에만이 메모리를 할당 클래스를 쓰고 싶다 마십시오. 메모리 누수를 피하고 할당되지 않은 메모리를 삭제하지 않으려면 wasCreated
을 도입했습니다. Create()
을 호출 할 때만 적용됩니다. 모든 TestStruct는 하나의 벡터에 저장해야합니다. 따라서 구현 된 코드에서 & ctor를 실행하고 두 코드 모두를 삭제합니다 & ctor.
이제는 새로운 메모리를 할당 할 때 벡터가 내 TestStruct의 기본 생성자를 interly 호출한다고 생각합니다. 그렇다면 왜 벡터가 메모리 할당시 기본 생성자를 호출하게할까요? 내 할당자가 필요합니까?
유효한 진입 점 중 하나를 사용하십시오. 'void main()'은 그들 중 하나가 아닙니다. – nvoigt
** - 1 ** '보이드 메인'. 그러지 마. –
@ Cheersandhth.-Alf +1 카운터. 'void main'은 더 이상 유용하지 않은 질문을하지 않습니다. – immibis