I am unclear if the correct code to pass an optional vector of ints to a function by reference is :
void test_func(std::optional<std::vector<int>&> vec)
or
void test_func(std::optional<std::vector<int>>& vec)
Any help much appreciated.
I am unclear if the correct code to pass an optional vector of ints to a function by reference is :
void test_func(std::optional<std::vector<int>&> vec)
or
void test_func(std::optional<std::vector<int>>& vec)
Any help much appreciated.
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)
A non-owning pointer is a nullable reference type.
void test_func(std::vector<int>* vec)
nullptr
? –
Felly 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. 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
.
void test_func(std::optional<std::vector<int>>& vec)
Here the std::optional
is passed by reference. 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.
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)
© 2022 - 2024 — McMap. All rights reserved.