gpt4 book ai didi

C++:对象和外部函数的生命周期

转载 作者:可可西里 更新时间:2023-11-01 16:07:06 27 4
gpt4 key购买 nike

假设我想调用对象的外部函数来在主体构造函数内部执行一些检查。由于对象的生命周期从构造函数的主体完成执行开始,这是一个不安全的设计吗?

struct A;

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

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

我的意思是,我正在调用一个尚未激活的对象的外部函数。这是未定义的行为吗?

相关问题:如果我将该检查函数作为成员函数(静态或非静态),标准对在构造函数外部但在类内部使用非事件对象有何规定?

类和它的用户的观点之间的生命周期概念有什么区别(一种类内和类外生命周期)?

最佳答案

A 的生命周期不会在 check() 被调用时开始,因为从 [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.

然而,尽管 A 的生命周期尚未开始,该标准还在 [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 中),所以我认为没有理由以生命周期为由排除前者。

关于C++:对象和外部函数的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30350127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com