1

考虑以下 C++11 代码,它是我能想到的最小的复制器:

#include <iostream>
#include <boost/range/adaptor/transformed.hpp>

std::vector<uint32_t> myTransform(const std::vector<uint32_t>& iVector) {
  return iVector;
}

int main() {
  const std::vector<std::vector<uint32_t>> theInput{{1, 2}};
  const auto myRange = theInput | boost::adaptors::transformed(myTransform);

  for (auto it = boost::begin(myRange); it != boost::end(myRange); ++it) {
    for (auto it2 = boost::begin(*it); it2 != boost::end(*it); ++it2) {
      std::cout << *it2 << std::endl;
    }
  }
}

我希望它打印以下输出:

1
2

...但它会打印(参见http://cpp.sh/8yivt):

0
0

但是,如果我更改myTransform为返回这样的引用:

const std::vector<uint32_t>& myTransform(const std::vector<uint32_t>& iVector) {
  return iVector;
}

...然后我得到预期的输出(参见http://cpp.sh/5brvl)。

我无法从Boost.Range 文档中找到对此行为的任何解释。我的代码不正确吗?我的期望不正确吗?这是 Boost.Range 中的错误/已知限制吗?

这个问题的目的首先是要了解为什么它会以意想不到的方式表现,并且只是偶然地找到解决方案。

4

0 回答 0