을 psomeclass을 삭제해야합니다. 생성자가 초기화를 완료하지 않았기 때문에 생성자가 예외를 throw하고 일부 멤버가 생성자 호출에 도달하지 못했기 때문에 클래스 멤버의 소멸자가 이 아닌이 호출됩니다. 소멸자는 클래스의 소멸자 호출 중에 만 호출됩니다. 그것은 단지 의미가 있습니다.
이 간단한 프로그램에서이를 보여줍니다. 다음과 같은 출력 (g를 사용하여 ++ 4.5.2)와
#include <stdio.h>
class A
{
int x;
public:
A(int x) : x(x) { printf("A constructor [%d]\n", x); }
~A() { printf("A destructor [%d]\n", x); }
};
class B
{
A a1;
A a2;
public:
B()
: a1(3),
a2(5)
{
printf("B constructor\n");
throw "failed";
}
~B() { printf("B destructor\n"); }
};
int main()
{
B b;
return 0;
}
:
A constructor [3]
A constructor [5]
B constructor
terminate called after throwing an instance of 'char const*'
Aborted
생성자가 실패하는 경우는 도중에 다음 그것을 처리하는 것은 귀하 자신의 책임입니다. 더 나쁜 것은 예외가 기본 클래스의 생성자에서 발생할 수 있습니다! 이러한 경우를 처리하는 방법은 "함수 try 블록"을 사용하는 것입니다 (그러나 그래도 부분적으로 초기화 된 객체의 삭제는주의 깊게 작성해야합니다). 당신이 그것을 실행하는 경우
#include <stdio.h>
class A
{
int x;
public:
A(int x) : x(x) { printf("A constructor [%d]\n", x); }
~A() { printf("A destructor [%d]\n", x); }
};
class B
{
A * a1;
A * a2;
public:
B()
try // <--- Notice this change
: a1(NULL),
a2(NULL)
{
printf("B constructor\n");
a1 = new A(3);
throw "fail";
a2 = new A(5);
}
catch (...) { // <--- Notice this change
printf("B Cleanup\n");
delete a2; // It's ok if it's NULL.
delete a1; // It's ok if it's NULL.
}
~B() { printf("B destructor\n"); }
};
int main()
{
B b;
return 0;
}
당신은 할당 된 객체가 파괴 해제됩니다 예상 출력을 얻을 것이다 :
문제에 대한 올바른 접근 방식은 다음과 같은 것이 될 것이다.
B constructor
A constructor [3]
B Cleanup
A destructor [3]
terminate called after throwing an instance of 'char const*'
Aborted
추가 공유 기능을 사용하여 스마트 공유 포인터로 해결할 수 있습니다.
class C
{
std::shared_ptr<someclass> a1;
std::shared_ptr<someclass> a2;
public:
C()
{
std::shared_ptr<someclass> new_a1(new someclass());
std::shared_ptr<someclass> new_a2(new someclass());
// You will reach here only if both allocations succeeded. Exception will free them both since they were allocated as automatic variables on the stack.
a1 = new_a1;
a2 = new_a2;
}
}
행운을 빌어 요, Tzvi이 유사한 생성자를 작성.
나는 알고있다, 나는 몹시 괴로운 성격을 가지고있다. 나는 그것을 도울 수 없다. 내 2 센트 : 명세서 objsomeclass = someclass(); 불필요합니다. 생성자의 본문에는 objsomeclass가 이미 기본값으로 초기화되어 있습니다. 아래의 objsomeclass (someclass())는 의미가 없습니다. –
동의하지만 someclass에 명시 적 생성자가 있다고 생각합니다. 개체에 초점을 맞추고 싶습니다. 생성자에서 생성되었습니다. – yesraaj
예, 알고 있습니다. 그래서 내가 딱딱한 소리를 질렀다. BTW 생성자 base() public 일 수 있습니다. –