转换谓词,通过引用返回局部变量
Transform predicate returning local variable by reference
在以下代码中,我试图将std::vector<char>
复制到std::vector<uint8_t>
中。为了避免编译器警告,我在std::transform
的谓词内做显式转换,而不是使用std::copy
,像这样
std::vector<char> buf(10, 10);
std::vector<uint8_t> u(10);
std::transform(std::begin(buf), std::end(buf), std::begin(u),
[](uint8_t val)->decltype(*std::begin(u)){
return static_cast<decltype (*std::begin(u))> (val);
});
对于这段代码,我得到编译器警告说,我试图通过引用返回一个局部变量val
。
为什么会这样?如何修复?
编译器是正确的。在lambda的返回类型中:
decltype(*std::begin(u))
对std::vector<T>::begin()
返回的迭代器进行解引用,根据u
的const
限定返回T&
或T const&
。其次,lambda显示未定义行为,因为您正在返回对临时val
的引用。
要解决您的问题,可以使用std::decay_t
std::decay_t<decltype(*std::begin(u))>
这导致我们:
std::transform(std::begin(buf), std::end(buf), std::begin(u),
[](auto val)-> std::decay_t<decltype(*std::begin(u))> {
return val;
});
------------------------------------------------------
如果类型是隐式可转换的,您可以简单地执行:
std::vector<uint8_t> u(std::begin(buf), std::end(buf));
或者,对已创建的u
:
u.assign(std::begin(buf), std::end(buf));
另一方面,对于其他一些复杂类型,一个普通的循环并不坏:
for(const auto& k : buf)
u.emplace( k.converted() ); //Assuming you must call a conversion function
您实际寻找的是vector
的范围构造函数:
std::vector<char> buf(10, 10);
std::vector<uint8_t> u(buf.begin(), buf.end());
这比包含transform()
的解决方案更有效,更容易阅读。
相关文章:
- 如何通过引用返回对象
- 函数如何使用引用返回所需的数字?
- 如何防止引用返回的私有结构的突变
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 通过引用返回的变量的范围
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 运算符重载C++类中的引用返回
- C++对象引用返回不同的值
- 解释通过从函数引用返回数组的语法
- 具有引用返回类型的重写方法上的协变返回类型无效
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- 为什么我在函数中使用引用并通过引用返回它仍然有效?
- 直接在 C++ 中将值分配给引用返回类型
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 可以通过常量引用返回默认参数的值吗?
- 按值与右值引用返回
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 当我使用按引用返回时,我不知道这些代码之间的区别
- 为什么通过引用返回向量比通过移动返回要快得多?
- 通过引用返回包含对象的向量