c++ - 你能初始化 unique_ptr 的 "static const vectors"吗? (C++17 与 GCC 7.3)

标签 c++ gcc stl c++17

我正在尝试创建一个 static const默认对象(规则)的列表太大而不能经常复制,因此我想将它们存储在 vector 中的 unique_ptr<> .我注意到类似的问题已经进行了几次,但我不清楚这是否真的可行(我倾向于不可行)。即

  1. 你不能使用 initializer_listunique_ptr因为对成员的访问是 const 导致复制操作。
  2. 您不能通过引用传递临时变量,从而导致复制操作。

因此两者:

static const std::vector<std::unique_ptr<std::string>> kStrings = {
  std::unique_ptr<std::string>(new std::string("String 1")),
  std::unique_ptr<std::string>(new std::string("String 1"))
};

static const std::vector<std::unique_ptr<std::string>> kStrings(
  std::unique_ptr<std::string>(new std::string("String 1")),
  std::unique_ptr<std::string>(new std::string("String 1"))
);

不可行。

我是不是误会了?有没有另一种方法来初始化这样的 vector ,或者这是重新考虑设计的情况?我能想到的最简单的替代方法是创建对象 a static const然后将它们引用为原始指针。例如:

static const std::string kString1 = "String 1";
static const std::string kString2 = "String 2";

static const std::vector<const std::string*> kStrings = {&kString1, &kString2};

感觉很恶心,但是代码接口(interface)保持相对不变,并且由于它没有离开类的范围,所以对用户来说也是透明的。

感谢任何想法、更正或更好的替代方案。

编辑 - 关于this question ,我已经测试了该解决方案并且它也有效。我的解决方案问题是它启用了 initializer_list以它们不是为使用而设计的方式使用,我不知道会产生什么意想不到的后果,如果有的话。

最佳答案

Am I misunderstanding? Is there another way to initialize such a vector

有一个函数,它返回一个非常量 vector 以用作初始值设定项。它甚至不必命名。它可以是立即调用的 lambda。

static const std::vector<std::unique_ptr<std::string>> kStrings = [] {
  std::vector<std::unique_ptr<std::string>> ret;
  // populate ret
  return ret;
}(); // <-- Invoke the lambda immediately after defining it. 

现在您可以拥有复杂的初始化逻辑并将 kStrings 仍然视为 const。此外,编译器很可能会完全内联 lambda,因此甚至不会有函数调用的开销。它真的是吃你的蛋糕,也吃它。

尽管有人想知道为什么要使用指向字符串(一种值类型)的唯一指针 vector 。 vector 已经拥有它的内容。所以你可能会减少中间人,这也会简化初始化。

关于c++ - 你能初始化 unique_ptr 的 "static const vectors"吗? (C++17 与 GCC 7.3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51229195/

相关文章:

c - 如何为 GCC 代码指定手动重定位?

STL - STL count_if 的标准谓词

c++ - 为什么在以空映射开始的feed时std::next卡住了

c++ - 使用包含类数据的 PrivateClass 有什么好处?

c - 调试错误 "Werror=unused-but-set-variable"

C++ 代码崩溃并出现无限循环

c++ - 必须将文件编译为不同扩展类型的原因

c++ - 为什么没有 std::erase?

c++ - std::stringstream 中的空格插入失败

c++ - 使用 Valgrind 抑制 Qt 内存泄漏的文件