【发布时间】:2020-04-21 14:21:09
【问题描述】:
我正在尝试打印从函数返回的跨度,但它没有捕获数据。如何正确地从函数返回跨度?
#include <gsl/span>
#include <iostream>
#include <memory>
gsl::span<int> res(){
std::array<int, 3> str{100, 200,300};
gsl::span<int> a{str};
return gsl::span<int>(a.data(), a.size());
}
int main() {
auto test{res()};
for (const auto &i: test)
std::cout << i << std::endl;
}
【问题讨论】:
-
只有在
span引用的缓冲区仍然有效时,才能访问span的内容。在这种情况下,它引用了一个超出范围的对象。所以你应该直接返回str,或者使用vector,或者实际提供存储的东西。