I fully understand the code below is wrong;It will release the resource twice.But my question is that whether this code is correct or not if reedited it as follow.Is there any potential problem that i should be aware of?I would be grateful to have some help on this question.
The wrong code:
#include<memory>
#include<iostream>
using std::shared_ptr;
struct S
{
shared_ptr<S> dangerous()
{
return shared_ptr<S>(this); // don't do this!
}
~S()
{
std::cout << "destructor" << std::endl;
}
};
int main()
{
shared_ptr<S> sp1(new S);
shared_ptr<S> sp2 = sp1->dangerous();
return 0;
}
The reedited one:
#include<memory>
#include<iostream>
using std::shared_ptr;
class S
{
public:
S() = delete;
static shared_ptr<S> dangerous()
{
return shared_ptr<S>(); // don't do this!
}
~S()
{
std::cout << "destructor" << std::endl;
}
};
int main()
{
shared_ptr<S> sp1 = S::dangerous();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire