【问题标题】:Returning RValueRef: warning C4172: returning address of local variable or temporary返回 RValueRef:警告 C4172:返回局部变量或临时地址
【发布时间】:2019-06-15 07:16:54
【问题描述】:

我有一个函数可以从 storage-ptr 中移动一个 int:

int&& MoveFromStorage(void const* p)
{
    return static_cast<int&&>(*static_cast<int*>(const_cast<void*>(p)));
}

int main()
{
    int i = 10;
    int&& iRValRef = MoveFromStorage(&i);
}

使用 MSVC 2017 编译此函数会导致 warning C4172: returning address of local variable or temporary。我没有使用 clang 或 gcc 收到此警告。我没有看到我在哪里返回局部变量或临时地址。这是 MSVC 中的错误吗?

编辑

也许我可以提供更多上下文:我自己编写了一个 std::variant 并为访问函数编写了以下代码:

template<class AlternativeType>
inline AlternativeType _cast_to(void const* variant_storage)
{
    typedef typename std::remove_reference<AlternativeType>::type without_ref;
    return static_cast<AlternativeType>(*static_cast<without_ref*>(const_cast<void*>(variant_storage)));
}

template<class AlternativeType, class Visitor>
inline auto _visit_impl(Visitor&& vis, void const* variant_storage)
    -> decltype(std::forward<Visitor>(vis)(_cast_to<AlternativeType>(variant_storage)))
{
    return std::forward<Visitor>(vis)(_cast_to<AlternativeType>(variant_storage));
}

然后我通过填充数组来使用这些函数:

FPtrType arr[] =  { _visit_impl<QualifiedCurrentType>... };

而 QualifiedCurrentType 变体的第 I 个类型具有应用的变体的常量性和引用性。 IE。如果变体通过 r-value-ref 传递,则 QualifiedCurrentType 将是某个其他类型的 RvalueRef。对于这些情况,_cast_to 会生成警告。

【问题讨论】:

标签: c++


【解决方案1】:

我无法解释,但以下更改帮助我修复了代码:

template<class AlternativeType>
inline AlternativeType _cast_to(void const* variant_storage)
{
    typedef typename std::remove_reference<AlternativeType>::type without_ref;
    without_ref* typedPointer = static_cast<without_ref*>(const_cast<void*>(variant_storage));
    return static_cast<AlternativeType>(*typedPointer);
}

所以解决方案是在应用进一步的强制转换之前存储一些中间类型的指针。

【讨论】:

    猜你喜欢
    • 2011-04-13
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多