Build two shared_ptr objects from one pointer

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.

+3
4

, , shared_ptr shared_ptr.

shared_ptr<SX> sp1( new SX );
shared_ptr<SX> sp2( sp1 );

SX , .

+3

, , , . shared_ptr - , . ( ) shared_ptr , . , :


typedef boost::shared_ptr FilePtr;
void FileClose( FILE* pf ) { if ( pf ) fclose( pf ); }
FilePtr pfile( fopen( "filename" ), FileClose );

, .. .. RAII .

+2
source

You can see how boost solves it with shared_from_this . Here is the code .

+1
source

Source: https://habr.com/ru/post/1708465/


All Articles