나는 shared_ptr 및 weak_ptr에 대해 학습하기 시작했습니다. 이론 상으로는 모든 것이 단순 해 보입니다. 하지만 테스트를 시작했을 때, 음 ...이 간단한 프로그램이 있습니다.shared_ptr.reset() 삭제하지 않음
#include <iostream>
#include <memory>
using namespace std;
class Second
{
public:
Second()
{
cout << "Second created" << endl;
}
~Second()
{
cout << "Second deleted" << endl;
}
};
class Main
{
public:
shared_ptr<Second> second;
Main()
{
cout << "Main created" << endl;
second = make_shared<Second>(*(new Second()));
}
~Main()
{
second.reset();
cout << "Main deleted" << endl;
}
};
void fun()
{
shared_ptr<Main> main = make_shared<Main>(*(new Main()));
}
int main()
{
cout << "Program started" << endl;
fun();
cout << "Program ended" << endl;
return 0;
}
문제는 두 번째가 삭제되지 않는다는 것입니다. 세드릭
Program started Main created Second created Main deleted Program ended
: 여기 내 출력은? 나는 shared_ptr과 그 마지막 shared_ptr을 리셋하면 객체가 자동으로 삭제된다는 것을 알았다.
이게 뭐야 :'make_shared (* (새 초)));'? 힙에 객체를 만든 다음 다른 객체에 복사합니다. 원본은 결코 삭제되지 않습니다! 'make_shared ();' –
@ DeX3r'make_shared'의 매개 변수를 사용하여 생성자가 매개 변수를 필요로하는 클래스를 초기화해야합니다. – quamrana