In a discussion with a colleague regarding the use of std::optional
this came up. Say we have a function that takes 2 unique pointers and the 2nd argument is optional i.e. it can be null
.
It can be implemented either via using std::optional
or just setting the default value of 2nd param as nullptr
i.e.
#include <string>
#include <functional>
#include <iostream>
#include <optional>
#include <memory>
class A {
// body of class
};
class B {
// body of class
};
void func_with_optional(std::unique_ptr<A> aptr,
std::optional<std::unique_ptr<B>> bptr = std::nullopt) {
std::cout << "func with std::optional called\n";
}
void func_without_optional(std::unique_ptr<A> aptr,
std::unique_ptr<B> bptr = nullptr) {
std::cout << "func without std::optional called\n";
}
unless the second argument is class&
say B&
or any other type where default can't be specified say we only have one argument and that's also optional or an optional return value. I see no difference in the above two functions. The default value serves sufficiently enough without the need of std::optional
.
Am I missing something here? Does the std::optional
one or the default value version has more leverage over another. May be, answer lies in lines of best coding practices and not necessarily in what compiler allows or not.
What is the more generally accepted version in the industry?