Dangling References leading to undefined behavior

五迷三道 提交于 2019-12-25 04:04:49

问题


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.


回答1:


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 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.




回答2:


Will this help alleviate the possibility of dangling references that can lead to undefined behavior?

It would... but each instance of this wrapper will hold their own object, and so it therefore won't achieve your original goal of "multiple containers would hold the same referenced objects"

Also, the implicit copy/move constructor/assignment will copy/move the internal object, but the copy of the reference will refer to the original object instead of the copy - which again leads to possibility of dangling references.

The reference of this wrapper appears to serve no purpose.



来源:https://stackoverflow.com/questions/41485042/dangling-references-leading-to-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!