Francis Cugler
Francis Cugler

Reputation: 7905

Dangling References leading to undefined behavior

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.

Upvotes: 0

Views: 149

Answers (2)

eerorika
eerorika

Reputation: 238351

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.

Upvotes: 1

Kamil Koczurek
Kamil Koczurek

Reputation: 706

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.

Upvotes: 2

Related Questions