我清楚地知道下面的前一个代码是错误的,因为它两次释放资源。但我的问题是后者(检查https://godbolt.org/z/ndsHtX)是否正确。也许它是正确的,因为输出的终止。我应该注意任何潜在的问题吗?我将不胜感激在这个问题上能得到一些帮助。
错误的代码:
#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;
}
我不确定是对还是错的一个:
#include<memory>
#include<iostream>
using std::shared_ptr;
class S
{
public:
//S() = delete;
int m_num;
public:
static shared_ptr<S> dangerous()
{
return make_shared<S>(); // don't do this!
}
void setNum(int num)
{
m_num = num;
}
~S()
{
std::cout << "destructor" << std::endl;
}
};
int main()
{
shared_ptr<S> sp1 = S::dangerous();
shared_ptr<S> sp2 = sp1;
std::cout << sp1.use_count() << std::endl;
std::cout << sp2.use_count() << std::endl;
sp1.get()->setNum(99);
sp1.get()->m_num;
std::cout << "hello" << std::endl;
return 0;
}