导致未定义行为的悬空引用 [英] Dangling References leading to undefined behavior

查看:48
本文介绍了导致未定义行为的悬空引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾在这里问过一个关于引用和未定义行为的上一个问题:上一个问题并基于给出的答案和一些评论中的评论,例如 user2079303 的评论,他们声明了这一点:

I had asked a previous question about references and undefined behavior here: previous question and based on the answer given and some of the comments such as the comment by user2079303 where they stated this:

如果您有一个主"容器,其中包含从不修改的对象本身(而不是引用),并且其他容器对主容器有引用,则引用包装器可以正常工作

A reference wrapper works fine, if you have one "master" container that contains the objects themselves (not references) that is never modified, and other containers have references to the master

我的新问题变成了这样:这是否有助于减轻可能导致未定义行为的悬空引用的可能性?

My new question becomes this: Will this help alleviate the possibility of dangling references that can lead to undefined behavior?

template<class T>
class Wrapper {
private:
    T object;
public:
    T& referenced_object;
    explicit Wrapper( T& obj ) : object(obj), referenced_object( object ) {}
};

它将以与上一个问题中所见相同的方式使用,其中多个容器将保存相同的引用对象,如果一个对象在一个容器中被修改,则该对象的相应引用也将在另一个容器中被修改.

It would be used in the same manner as seen in the previous question where multiple containers would hold the same referenced objects where if one object is modified in one container, the corresponding reference of that object will also be modified in the other container.

推荐答案

这样的包装器没有意义,如果您存储副本本身,则不需要参考.当您移动此对象时,您的引用将变得无效(例如,当它存储在 std::vector 中并重新分配内存时).

Such wrapper makes no sense, if you store the copy itself then there's no need for reference. And your reference becomes invalid when you move this object (eg. when it's being stored in std::vector and it reallocates memory).

References 和 std::reference_wrapper 工作得很好,但不要移动你的对象.将对象保存在 std::list 中可保证它们不会被移动,因此您可以使用它并将多个容器中的引用指向其对象.

References and std::reference_wrapper work just fine, but don't move your object. Keeping objects in std::list guarantees that they won't be moved, so you can use it and point references in multiple containers to its objects.

这篇关于导致未定义行为的悬空引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆