
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;} 输出……提出了一些额外的难题 – 例如.为什么在调用operator()之前第一个dstr事件发生?在最后一次失败的析构函数调用之前还要注意“2”.
from cstrfrom dstr1from dstrbind_copy(73365) malloc: *** error for object 0x1001b0: double free*** set a breakpoint in malloc_error_break to deBUGfrom dstrbind_copy(73365) malloc: *** error for object 0x1001b0: double free*** set a breakpoint in malloc_error_break to deBUG2from dstrbind_copy(73365) malloc: *** error for object 0x1001b0: double free*** set a breakpoint in malloc_error_break to deBUG
所以问题是:任何人都可以简单地解释一下这个顺序,以及哪种副本可以绑定?
…经过一番思考后,我意识到bind只是使用(这里是默认的)复制构造函数.在提供了这个cstr的一些自定义版本(带有内存分配和as-deep-as-one-wish许可版本的副本)后,输出变得干净(应该如此),但是谜题仍然存在:复制构造函数有三个调用.所以在这种情况下,boost :: bind会生成函数对象的三个副本.为什么以及以何种顺序? (对于嵌套的boost :: binds,这可能导致内部副本数量急剧增长.)
定义了cp-cstr的输出,并添加了一些“遗产标记”(“P”=父,每个cp cstr添加“-C”):
from cstr P from cp cstr P-C from cp cstr P-C-C from cp cstr P-C-C-C from dstr P-C-C P-C-C-C:1 from dstr P-C-C-C from dstr P-C P:1 from dstr P解决方法 见 here:
总结By default,bind makes a copy of the provIDed function object. boost::ref and boost::cref can be used to make it store a reference to the function object,rather than a copy. This can be useful when the function object is noncopyable,expensive to copy,or contains state; of course,in this case the programmer is expected to ensure that the function object is not destroyed while it’s still being used.
以上是内存溢出为你收集整理的c – boost :: bind内部副本/副本?全部内容,希望文章能够帮你解决c – boost :: bind内部副本/副本?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)