加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C:一个对象的生命周期和外部的功能

发布时间:2020-12-16 05:57:10 所属栏目:百科 来源:网络整理
导读:假设我想调用一个对象的外部函数来在body构造函数中执行一些检查.由于构造函数的正文完成执行后,对象的生命周期开始,是不安全的设计? struct A;void check(A const) { /* */ }struct A{ A() { check(*this); }}; 我的意思是,我正在调用和外部功能与一个尚未
假设我想调用一个对象的外部函数来在body构造函数中执行一些检查.由于构造函数的正文完成执行后,对象的生命周期开始,是不安全的设计?
struct A;

void check(A const&) { /* */ }

struct A
{
    A() { check(*this); }
};

我的意思是,我正在调用和外部功能与一个尚未活着的对象.这是不明确的行为吗?

相关问题:如果我把这个检查功能作为一个成员函数(静态或非静态的),那么这个标准对于在构造函数之外但是在类内部使用非活动对象呢?

在课堂观点与用户之间(一类课外与课外生活)有什么不同的终身概念?

解决方法

当调用check()时,A的生命周期将不会开始,因为from [base.life]:

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained,and
  • if the object has non-vacuous initialization,its initialization is complete.

A具有非空的初始化.它的初始化完成时,从[class.base.init] / 13:

In a non-delegating constructor,initialization proceeds in the following order:

  • — Finally,the compound-statement of the constructor body is executed.

然而,尽管一开始还没有开始,该标准还在[class.base.init] / 16:

Member functions (including virtual member functions,10.3) can be called for an object under construction… However,if these operations are performed in a ctor-initializer (or in a function called directly
or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed,the result of the operation is undefined.

关于一生的问题,没有区别:

void check(const A& ) { .. }
struct A { 
    A() { check(*this); } 
};

和:

struct A {
    void check() const { .. }
    A() { check(); }
};

后者被明确允许(因为它不在一个ctor-initializer中),所以我没有理由以终身理由排除前者.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读