在编程中赋值是先把左侧对象销毁?C++中能否实现“静态”初始化容器

时间:2017-12-29 11:24:01   浏览:次   点击:次   作者:   来源:   立即下载

a=a,a已经先被销毁了,为什么还能完成赋值

对于有 non-trivial destructor 的类来说,self-assignment 是要注要的。

如果写成这样的 copy assignment,是不用理会 self-assignment 的,但会有额外的 copy/move constructor 调用消耗:

T // resources are exchanged between *this and arg return *this;} // destructor of arg is called to release the resources formerly held by *this

如果原来的资源还可再利用,就可以写成这种形式:

T // destroy storage in this /* reset size to zero and mArray to null, in case allocation throws */ mArray = new int[/*size*/]; // create storage in this } /* copy data from other\'s storage to this storage */ } return *this;}对于传进 const T& 的 assignment operator,需要检测 self-assignment。

例子来自 operator overloading

突然想到了这个,模板元 编译的时候计算斐波那契数列

template struct Fibonacci { enum { result = ① }; };template struct Fibonacci { enum { result = ① }; };template struct Fibonacci { enum { result = Fibonacci::result + Fibonacci::result }; };

直接写不可以,编译期初始化更没希望

但是如果想达到①个类似于C#里面第①次调用前初始化的效果,间接写还是有办法的,但我不知道下面这样写是不是有危险,反正我的项目里这样做了。大意是这样的

static unordered_map& bar()

{

static unordered_map baaar;

return bar;

}

class initializer

{

initializer()

{

..干①些初始化baar的事情;;;

}

}

static initializer bar_initi;

收起

相关推荐

相关应用

平均评分 0人
  • 5星
  • 4星
  • 3星
  • 2星
  • 1星
用户评分:
发表评论

评论

  • 暂无评论信息