I have a problem from “The C++ Standard Library Extensions”:
Exercise 6
I said in Section 2.4.2
that you shouldn’t construct two
shared_ptr objects from the same
pointer. The danger is that both
shared_ptr objects or their progeny
will eventually try to delete the
resource, and that usually leads to
trouble. In fact, you can do this if
you’re careful. It’s not particularly
useful, but write a program that
constructs 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 it is a good solution–because i don’t want solving it by use constructor. can anyone give me a better one?
thx, forgive my bad english.
I got the “STANDARD” answer from boost doc :
http://www.boost.org/doc/libs/1%5F38%5F0/libs/smart%5Fptr/sp%5Ftechniques.html#another_sp