5

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.

oracle3001
  • 1,090
  • 19
  • 31
  • 1
    The second one. – Jans Dec 09 '18 at 02:46
  • 1
    What Is the use case here? If the vector doesn't need to be modified then you could pass by const reference and use a default parameter. – NathanOliver Dec 09 '18 at 02:54
  • That is the way I did have it in my code, but I found this new functionality and it will just make the function a tiny bit more efficient. Basically the vector of ints are indices and an absence of argument equals pick all indices. – oracle3001 Dec 09 '18 at 02:55
  • 1
    Consider two overloaded functions, one that takes no parameters, and one that takes the vector by reference. Sometimes, the least complicated solution is often the cleanest one. – Sam Varshavchik Dec 09 '18 at 03:01
  • 3
    Since you cannot have optional references, there shouldn't be any lack of clarity. – Kerrek SB Dec 09 '18 at 03:02
  • 1
    This is bad usage of optional make your code unreadable – jean Dec 09 '18 at 03:39

3 Answers3

6

A non-owning pointer is a nullable reference type.

void test_func(std::vector<int>* vec)
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
5

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.

Kostas
  • 4,061
  • 1
  • 14
  • 32
  • Thanks. Actually neither do quite what I hoped to do / are problematic. I wanted to pass an optional vector of ints, but ideally I don't want to be copying them. I am trying to add some new flexibility to some legacy code, which was hoping to do so with minimum alterations via an optional parameter. – oracle3001 Dec 09 '18 at 03:27
2

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)
JVApen
  • 11,008
  • 5
  • 31
  • 67