将向量<unique_ptr<T>>转换为向量<unique_ptr<const T>>

Nan*_*Hua 1 c++ c++11

如何转换vector<unique_ptr<T>>vector<unique_ptr<const T>>

使用有什么缺点reinterpret_cast吗?在 C++11 及更高版本中推荐的方法是什么?

vector<unique_ptr<const T>> Get() {
  vector<unique_ptr<T>> some;
  ...
  // Any better way to do this?
  return *(reinterpret_cast<vector<unique_ptr<const T>>*>(&some));
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

您可以通过将旧向量的内容移入其中来构造新向量:

#include <iterator>
#include <memory>
#include <vector>

std::vector<std::unique_ptr<T>> v; // ...

std::vector<std::unique_ptr<const T>> cv(
    std::make_move_iterator(v.begin()),
    std::make_move_iterator(v.end()));
Run Code Online (Sandbox Code Playgroud)

您提出的reinterpret_cast结果会导致未定义的行为。

您问题的总体主题是,您试图将一个事物的资源管理处理程序视为另一个相关事物的资源管理处理程序。这是一个有问题的概念,因为处理程序确实需要知道它到底在处理什么,但它在某种程度上忽略了重点。你真正想做的是传达对所处理事物的看法。在当前上下文中,您可以获取已处理的事物(一个T指针),并使用通常的语言规则将转换为const T指针,这将按预期工作并避免谈论处理程序对象(唯一指针)。