Detect dangling references to temporary

坚强是说给别人听的谎言 提交于 2019-11-30 06:18:27

You can detect misuses of this particular API by adding an additional overload:

const T& get_or_default(T&& rvalue) = delete;

If the argument given to get_or_default is a true rvalue, it will be chosen instead, so compilation will fail.

As for detecting such errors at runtime, try using Clang's AddressSanitizer with use-after-return (ASAN_OPTIONS=detect_stack_use_after_return=1) and/or use-after-scope (-fsanitize-address-use-after-scope) detection enabled.

Serge Ballesta

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<const T&>(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...

You could try out lvalue_ref wrapper from Explicit library. It prevents the unwanted binding to a temporary in one declaration, like:

const T& get_or_default(lvalue_ref<const T> def)
{
    return has ? value : def.get();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!