唯一指针作为默认参数

Unique Pointer as default parameter

我正在尝试将包装为唯一指针的空指针作为函数的默认参数。仅使用指针 header 可能看起来像这样

double f(A* vec = nullptr);

因为我确实需要使用 unique_ptr,所以我尝试将其更改为

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

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

导致错误

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

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

分别。有没有办法做到这一点?我对 C++ 比较陌生,所以答案可能很明显。


与问题无关,但对我选择unique_ptr的解释:参数vec用作f中迭代的起始值,改进后的值随指针一起返回。计划是,如果没有给出起始值,则将指针设置为 nullptr,并在程序期间计算起始值。但是,由于我生成了一个新的 object,据我所知,在裸指针上使用 unique_ptr 会更安全。

第二个错误是因为您将非常量引用绑定到右值(它有点像这样说)。如果这是必须的,则不能使用默认值,也不能使用 const 引用:

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

我会说你在这里有两个选择。

1) 函数不 拥有 指针,它只是使用它。在这种情况下传递原始指针或(更好)引用(如果nullptr不是一个选项)。

// correct way to express a call to a non-owning function.
double f(A* vec = nullptr);

调用代码将使用如下函数:

std::unique_ptr<A> vec;

f(vec.get()); // pass the raw pointer to the function

2) 该函数需要管理指针的生命周期或重新设置指针(拥有它),在这种情况下接受 std::unique_ptr by .

// way to express transfer of ownership to a function
double f(std::unique_ptr<A> vec = std::unique_ptr<A>());

如果函数需要获取指针的所有权,则确实没有必要接受引用。

在讨论中出现了第三个选项。

3) 如果你在 otherwise 它将使用自己的内部指针。

这很不寻常,但您可以像这样使用一对重载函数来做到这一点:

// way to express a function that modifies a smart pointer
// (for example reseating it)
double f(std::unique_ptr<A>& vec);

// version where the uses doesn't want to supply the pointer
// and doesn't care about the modified value.
double f() 
{
    std::unique_ptr<A> vec; // a dummy
    f(vec); // pass in the dummy
}
double f(std::unique_ptr<A>& vec = nullptr);

不起作用,因为编译器必须从 nullptr 创建一个临时的 std::unique_ptr。你用过吗

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

编译器会接受它。

一种解决方法是超载。

double f(std::unique_ptr<A>& vec)
{
   return 0;
}

double f()
{
   std::unique_ptr<A> vec = nullptr;
   return f(vec);
}