c++ - 引用未初始化的对象

标签 c++ reference initialization language-lawyer

在解释问题之前,我想指出我知道给定的示例是错误的代码。我已经在查看 std::shared_ptr 以更合理的方式实现我的目标。这篇文章的原因只是我的好奇心和学习新东西的愿望。预先感谢您的帮助!

今天我的解析器代码有点乱。优化的东西等。我专注于一些对象实例,这些实例在解析过程中一直被不必要地克隆。我有一个不太刻意的想法来创建几个全局实例并通过静态方法访问它们。无论如何(强烈简化)我以这个有点有趣的案例结束:

class class_a
{
    class_a();
    class_a& referenceToObject;
};

class_a& getGlobalObject();

class_a::class_a()
:referenceToObject(getGlobalObject())
{}

class_a object;
class_a object2;

class_a& getGlobalObject()
{
    return object2;
}

这显然意味着我做了很多非常错误的事情,但在这个分支中,优化是最重要的事情。

我对这样的代码在更广泛的编译器集合中会发生什么很感兴趣。 GetGlobalObject() 正在返回对未调用其构造函数的对象的引用。它仍然只返回引用 - 即指向编译时已知的内存空间(数据段或堆上某处,不知道)的指针。

假设没有任何东西会调用任何方法或 object2 引用的任何成员,这个例子是未定义的行为吗?

最佳答案

是的,传递对尚未构造的对象的引用是完全合法的,甚至以某些有限的方式使用此类引用也是完全合法的。

[basic.life] ... Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.allocation]), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if:
(7.1) the glvalue is used to access the object, or
(7.2) the glvalue is used to call a non-static member function of the object, or
(7.3) the glvalue is bound to a reference to a virtual base class ([dcl.init.ref]), or
(7.4) the glvalue is used as the operand of a dynamic_­cast ([expr.dynamic.cast]) or as the operand of typeid.

只要您没有执行上述任何操作,您就没有问题。

关于c++ - 引用未初始化的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48925166/

相关文章:

c++ - 在多线程应用程序中通过标准 I/O 获取输入

c++ - 这会导致引用超出范围后指向任何内容吗?

c++ - C++ 中的临时对象

hibernate - 初始化惰性实体的标准 JPA 方法

c++ - 基本 C++ 速度(初始化与添加)和比较速度

java - 如何从主方法(或任何方法)中的args[]初始化java中的常量,例如 "public static final Integer"

c++ - 以 mm/dd/yyyy 格式输入日期并将其拆分为 3 个单独的变量?

c++ - 我无法理解方程式的解,该方程式表示找到最小数,使得 x 加 y 等于 x 按位或 y

c++ - g++ 链接错误 : 'undefined reference to ' main'

c++ - 可以将 const 引用返回给私有(private)成员吗?