Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve dangling const ref

Tags:

c++

The following short program

#include <vector>
#include <iostream>

std::vector<int> someNums()
{
    return {3, 5, 7, 11};
}

class Woop
{
public:
    Woop(const std::vector<int>& nums) : numbers(nums) {}
    void report()
    {
        for (int i : numbers)
            std::cout << i << ' ';
        std::cout << '\n';
    }
private:
    const std::vector<int>& numbers;
};

int main()
{
    Woop woop(someNums());
    woop.report();
}

has a dangling reference problem, that no compiler seems to warn about. The issue is that temporaries can be bound to const-refs, which you may then keep around. The question then is; Is there a method of avoiding getting into this problem? Preferably one that does not involve sacrificing const correctness, or always making copies of big objects.

like image 355
sp2danny Avatar asked Mar 10 '20 11:03

sp2danny


People also ask

Can you modify a const reference C++?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.

Can const reference be modified?

Const Reference to a pointer is a non-modifiable value that's used same as a const pointer. Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it.

What is dangling reference in C++?

Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

Should I always use const reference?

Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter.


1 Answers

One way to make your class less vulnerable could be to add a deleted constructor that takes a right-ref. This would stop your class instance from making bindings to temporaries.

Woop(std::vector<int>&& nums)  =delete;

This deleted constructor would actually make the O/P code not compile, which may be the behaviour you are looking for?

like image 97
Gem Taylor Avatar answered Sep 19 '22 19:09

Gem Taylor