简体   繁体   English

使用std :: optional传递std :: vector <int> 通过引用来实现功能

[英]Use of std::optional to pass a std::vector<int> to a functional by reference

I am unclear if the correct code to pass an optional vector of ints to a function by reference is : 我不清楚是否通过引用将一个可选的int向量传递给函数的正确代码是:

void test_func(std::optional<std::vector<int>&> vec)

or 要么

void test_func(std::optional<std::vector<int>>& vec)

Any help much appreciated. 任何帮助非常感谢。

非拥有指针是可以为空的引用类型。

void test_func(std::vector<int>* vec)

Optional of references is not part of the standard library at the moment . 目前,可选的引用不是标准库的一部分

Both in principle make sense. 两者原则上都有道理。

void test_func(std::optional<std::vector<int>&> vec)

Here the std::optional is passed by value (copied), and so is the reference inside it. 这里std::optional按值传递(复制),其中的引用也是如此。 Copying a reference means it still points to the old object. 复制引用意味着它仍然指向旧对象。 This might create unexpected behavior, as there are two instances of std::optional pointing at the same std::vector . 这可能会产生意外行为,因为有两个std::optional实例指向同一个std::vector

void test_func(std::optional<std::vector<int>>& vec)

Here the std::optional is passed by reference. 这里std::optional通过引用传递。 You are accessing the same optional that was passed, no copying takes place. 您正在访问传递的相同选项,不会进行复制。

The second one is more intuitive imho and available in STL at the moment, so it's preferable . 第二个是更直观的imho,目前在STL中可用,所以它更可取

From what I'm aware, this isn't possible in the standard as one hasn't agreed upon the effects of an assignment. 据我所知,这在标准中是不可能的,因为一个人没有就任务的影响达成一致。

What you want to achieve is possible with a library feature: 使用库功能可以实现您想要实现的目标:

  void test_func(std::optional<std::reference_wrapper<std::vector<int>>> vec)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM