c++ - GCC 匿名未初始化
问题描述
我正在尝试创建类似于 的东西std::tuple
,一种使用可变参数模板和递归继承的编译时列表,如下面的实现所示。
我的问题是,尽管下面显示的实现在 msvc 上运行良好,但 clang 和 iccConstExprList::Get
在 gcc(主干版本)上总是返回 0。
如果在启用 -Wall -Werror 选项的情况下编译代码,gcc 会抛出以下错误:
anonymous is used uninitialized in this function [-Werror=uninitialized]
.
请注意,禁用优化后不会发生错误。
这是 gcc 实现中的错误还是遗漏了什么?
#include <type_traits>
template <typename... Args>
class ConstExprList;
template <typename Head, typename... Tail>
class ConstExprList<Head, Tail...> : public ConstExprList<Tail...>
{
public:
ConstExprList(const Head& head, const Tail&... tail) : ConstExprList<Tail...>(tail...), m_head(head) {}
template <std::size_t Idx>
inline typename std::enable_if<Idx == 0, Head>::type Get(void) const noexcept
{
return m_head;
}
template <std::size_t Idx>
inline typename std::enable_if<Idx != 0, Head>::type Get(void) const noexcept
{
return ConstExprList<Tail...>::template Get<Idx - 1>();
}
private:
const Head& m_head;
};
template <typename Head>
class ConstExprList<Head>
{
public:
ConstExprList(const Head& head) : m_head(head) {}
template <std::size_t Idx>
inline auto Get(void) const noexcept
{
static_assert(Idx == 0, "Index out of range");
return m_head;
}
private:
const Head& m_head;
};
int main(void)
{
ConstExprList<int, int> l(7, 3);
return l.Get<0>();
}
解决方案
该警告具有误导性,但指出了一个真正的问题。m_head
是对临时对象的引用。这不是会导致临时生命周期延长的上下文之一,因此您的引用会悬空。
推荐阅读
- azure-logic-apps - 存储在变量中的 json 的逻辑应用读取属性
- vb.net - 从字符串“”到类型“Double”的转换无效。
- matlab - 在配置 CMake 时选择使用 LibR 的 Matlab 包装器
- javascript - 在我的屏幕上绘制黑色画布不起作用,没有绘制黑色矩形
- apache - 如何仅使用 .htaccess 重定向我的主页
- vba - 如何在 Visio 绘图中查找所有形状并将每个形状添加到数组中?
- mysql - 如何正确地对具有条件的 UPDATE 列进行 SQL 请求?
- c# - 配对系统 N vs N 来自列表
- wxpython - 如何正确调整 wx.grid.Grid 的大小,使其不覆盖其他控件?
- apache-nifi - NiFi:使用 ExecuteScript 查询记录