mardi 30 janvier 2018

Unique Pointer as default parameter

I am trying to give the nullpointer wrapped as a unique pointer as the default argument to a function. Using only pointers the header might look like this

double f(A* vec = nullptr);

Since I do however need to use a unique_ptr, I tried to change it to

double f(std::unique_ptr<A>& A vec = nullptr);

or

double f(std::unique_ptr<A>& A vec = std::unique_ptr<A>(nullptr));

Which results in the errors

could not convert ‘nullptr’ from ‘std::nullptr_t’ to ‘std::unique_ptr&’

and

cannot bind non-const lvalue reference of type ‘std::unique_ptr&’ to an rvalue of type ‘std::unique_ptr’

respecively. Is there a way to do this? I am relatively new to C++, so the answer might be obvious.


Not relevant to the question, but an explanation for my choice of unique_ptr: The parameter vec is used as the start value for an iteration in f and an improved value is returned with the pointer. The plan was that if no start value is given the pointer is set to the nullptr and a start value is calculated during the program. Since I however generate a new object, it would from all I can see be safer to use unique_ptr over a naked pointer.

Aucun commentaire:

Enregistrer un commentaire