为什么通过条件操作员将参考传递到初始化列表会导致警告
Why does passing a reference through a conditional operator to an initializer list lead to a warning?
以下代码导致此警告(VC和GCC -WEXTRA):
warning C4413: 'ReferencingContainer::_vector' : reference member is initialized to a temporary that doesn't persist after the constructor exits
,但我不明白为什么。我以为我只是通过参考。
#include <vector>
struct Referencing
{
Referencing(int const &x) : _x(x) {}
Referencing(int const &x, int dummy) : _x(x > 5 ? x : throw "error") {} // bad code, warning is ok
int const &_x;
};
struct Container
{
std::vector<double> _vector;
};
struct ReferencingContainer
{
ReferencingContainer(Container const &container)
: _container(container)
, _vector(container._vector.size() > 0 ? container._vector : throw "error") // <-- warning occurs here
{}
Container const &_container;
std::vector<double> const &_vector;
};
int main()
{
Referencing test1(21);
Referencing test2(22, 0);
Container container;
ReferencingContainer referencingContainer(container);
return 0;
}
为什么编译器对我的代码不满意?我真的必须担心我的对象会引用临时性吗?
如果添加Wextra
标志,您将获得此警告:
px.cpp:12:83: warning: a temporary bound to ‘ReferencingContainer::_vector’ only persists until the constructor exits [-Wextra]
, _vector(container._vector.size() > 0 ? container._vector : throw "error") // <--- warning occurs here!
根据这个问题,这是编译器的错误:
关于临时临时构造成员构造成员
中的引用警告但是,正如Vsoftco所指出的那样,警告在版本5.1
中持续存在。其他相关问题:
- c 构造函数:垃圾,而const参考的初始化
- const参考是否会延长暂时的寿命?
一个可能的快速修复是将指针从?:表达式传递出来,然后解除它。
, _vector(*(container._vector.size() > 0 ? &container._vector : throw "error"))
那么,这里有什么问题?
编译器告诉您,通常他们对我们很有礼貌。由std :: vector ::大小的参考,我们有:
size_type size()const;
这意味着当您在行中调用它时会产生警告,size()
将返回_vector
大小的 copy 构造函数不超出范围。
相关文章:
- 复制列表初始化的隐式转换的等级是多少
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C++11 中的混合列表初始化
- 我可以列表初始化 std::vector 并完美转发元素吗?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++20 从括号中的值列表初始化聚合,不支持内部数组
- 如何在向量列表初始化时避免对象复制以及如何延长临时的生存期
- 默认参数和空列表初始化
- 如何在列表初始化中放置额外的语句?
- C++列表初始化允许多个用户定义的转换
- 列表初始化是否将原子初始化为零
- 使用可变模板列表初始化数组,并放置new
- 使用整数初始化列表初始化长双精度的向量
- 直接列表初始化的自动规则
- 使用初始化列表初始化unique_ptr的容器,继续
- 如何修复"非聚合无法使用初始值设定项列表初始化" <map>
- 直接列表初始化和复制列表初始化之间的差异
- 为什么我可以在不使用赋值运算符的情况下使用列表初始化普通数组
- C++ - 使用类中的初始值设定项列表初始化动态集