Detect dangling references to temporary

后端 未结 3 1109
一个人的身影
一个人的身影 2020-12-15 05:46

Clang 3.9 extremely reuses memory used by temporaries.

This code is UB (simplified code):

template 
class my_optional
{
public:
    bo         


        
3条回答
  •  情深已故
    2020-12-15 06:32

    That is an interesting question. The actual cause of the dangling ref is that you use an rvalue reference as if it was an lvalue one.

    If you have not too much of that code, you can try to throw an exception that way:

    class my_optional
    {
    public:
        bool has{ false };
        T value;
    
        const T& get_or_default(const T&& def)
        {
            throw std::invalid_argument("Received a rvalue");
        }
    
        const T& get_or_default(const T& def)
        {
            return has ? value : def;
        }
    };
    

    That way, if you pass it a ref to a temporary (which is indeed an rvalue), you will get an exception, that you will be able to catch or at least will give a soon abort.

    Alternatively, you could try a simple fix by forcing to return a temporary value (and not a ref) if you were passed an rvalue:

    class my_optional
    {
    public:
        bool has{ false };
        T value;
    
        const T get_or_default(const T&& def)
        {
            return get_or_default(static_cast(def));
        }
    
        const T& get_or_default(const T& def)
        {
            return has ? value : def;
        }
    };
    

    Another possibility would be to hack the Clang compiler to ask it to detect whether the method is passed an lvalue or an rvalue, by I am not enough used to those techniques...

提交回复
热议问题