Boost :: bind internal copy / s?

I was hoping to understand which internal instances of the function object activate :: bind do. Since the constructors of these objects do not seem to be called, I assumed that this was a kind of "very shallow copy", so I introduced dynamic memory allocations to get some errors. However, the code execution output below shows that there are three additional destructor calls for internal copies made by bind.

using namespace std; using namespace boost; class M{ int *somedata; public: M(){ somedata=new int[5]; cout<<"from cstr\n"; somedata[1]=0;} ~M(){cout<<"from dstr\n"; delete somedata;} int operator()(int i){ cout<<++somedata[i]<<endl; return 0;} }; int main() { M instM; bind<int>(instM,1)(); //bind<int>(&M::operator(),&instM,1)(); //this works with no errors, of course instM(1); //would not change the order of output return 0; } 

Conclusion ... contains some additional puzzles - for example. why does the first dstr event occur before the statement () is called? Also pay attention to "2" before the last unsuccessful call of the destructor.

 from cstr from dstr 1 from dstr bind_copy(73365) malloc: *** error for object 0x1001b0: double free *** set a breakpoint in malloc_error_break to debug from dstr bind_copy(73365) malloc: *** error for object 0x1001b0: double free *** set a breakpoint in malloc_error_break to debug 2 from dstr bind_copy(73365) malloc: *** error for object 0x1001b0: double free *** set a breakpoint in malloc_error_break to debug 

So the question is: can someone briefly explain in what order and which copies link make?

... After some thought, I realized that binding just uses the copy constructor (here by default). After providing some user version of this cstr (with memory allocation and as one copy with the full version of the copy), the result becomes clean (as it should be), but the puzzle remains: there are three calls to the copy constructor, So, in this case boost :: bind makes three copies of the function object. Why and in what order? (For nested boost :: binds, this can lead to a rather explosive increase in the number of internal copies.)

The output is set to cp-cstr, and some "heritage labels" are added ("P" = parent, each cp cstr adds "-C"):

  from cstr P from cp cstr PC from cp cstr PCC from cp cstr PCCC from dstr PCC PCCC:1 from dstr PCCC from dstr PC P:1 from dstr P 
+4
source share
1 answer

Look here :

By default, bind makes a copy of the provided function object. boost :: ref and boost :: cref can be used to store a reference to a function object, not a copy. This can be useful when the function object is not subject to copying, expensive copying, or contains state; Of course, in this case, the programmer must ensure that the function object is not destroyed while it is still in use.

+2
source

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


All Articles