I have a problem from the "Standard C ++ Library Extensions":
Exercise 6
I said in section 2.4.2 that you should not build two shared_ptr objects from the same pointer. The danger is that both shared_ptr or their offspring will eventually try to remove the resource, and this usually leads to trouble. In fact, you can do this if you are careful. This is not particularly useful, but write a program that builds two shared_ptr objects from the same pointer and deletes the resource only once.
below is my answer:
template <typename T>
void nonsence(T*){}
struct SX {
int data;
SX(int i = 0) :
data(i) {
cout << "SX" << endl;
}
~SX() {
cout << "~SX" << endl;
}
};
int main(int argc, char **argv) {
SX* psx=new SX;
shared_ptr<SX> sp1(psx),sp2(psx,nonsence<SX>);
cout<<sp1.use_count()<<endl;
return 0;
}
but I don’t think this is a good solution - because I don’t want to solve it with the use constructor. can anyone give me the best? thanks, sorry my bad english.