수업이 있습니다. 이 클래스가 인스턴스화 될 때 인스턴스를 목록에 추가하려고합니다. 개체가 삭제되면 목록에서 삭제됩니다.목록에서 개체를 자동으로 추가 및 제거
그래서 객체에 공유 포인터를 제공합니다. 그런 다음 공유 포인터에 약한 포인터 목록이 있습니다. 객체가 생성되면, 자신에 대한 공유 포인터를 생성하고, 그것에 약한 포인터를 만들고, 약한 포인터를리스트에 넣습니다.
개체가 파괴되면 공유 포인터도됩니다. 목록에있는 멤버에 액세스하려고 시도 할 때마다 만료되지 않았으며 사용 횟수가 0이 아닌지 확인합니다.이 작업에도 불구하고 목록 멤버가 삭제되면 여전히 충돌이 발생합니다. 왜? 나는 주변을 얻을 수 있습니까?
#include <iostream>
#include <memory>
#include <vector>
class test
{
private:
std::shared_ptr<test> self;
public:
int val;
test(int set);
test(test ©) = delete; // making sure there weren't issues
// with a wrong instance being deleted
};
std::vector<std::weak_ptr<test>> tests;
test::test(int set):
val(set)
{
this->self = std::shared_ptr<test>(this);
tests.push_back(std::weak_ptr<test>(this->self));
}
void printTests()
{
for (auto i = tests.begin(); i != tests.end(); i++)
{
if (i->use_count() == 0 || i->expired())
{
tests.erase(i);
continue;
}
std::cout << i->lock()->val << std::endl;
}
std::cout << std::endl;
}
int main(int argc, char **argv)
{
{
test t(3);
std::cout << "First tests printing: " << std::endl;
printTests();
} // SEGFAULTS HERE
std::cout << "Second tests printing: " << std::endl;
printTests();
return 0;
}
은 다음이 프로그램의 출력이 될 때 :
First tests printing:
3
Segmentation fault (core dumped)
나는 것입니다 거의 * 보장 * 당신'그 this-> 자기 = 표준 : : shared_ptr의 (이)'특히 실물,'테스트 t 있기 때문에, 당신이 생각하는 일을하지 않습니다 (3)', * stack *에있다. –
WhozCraig
스택에 있다는 것은 테스트가 범위 끝에서 파괴된다는 것을 의미합니다. 이는 내가 원하는 것입니다.내가하고 싶은 일을 내가 어떻게 또 할 것인가? – Avi
''std :: shared_ptr <>'는 공유 된 ptr obj가 파괴 될 때 포함 된 객체 포인터로 무엇을한다고 생각합니까? – WhozCraig