[英]What is a reference-to-pointer?
我最近看到一个被声明为的函数:
void func(type* ¶m);
我已经知道type* param
和type& param
之间的区别。 以上与他们有何不同? 什么时候使用这个? 这样做是否明智?
以上将不仅可以修改指向对象,还可以修改指针本身。 例如,请考虑以下代码:
void func(int*& ptr) {
*ptr = 1;
ptr = 0;
}
int main() {
int x = 0;
int* y = &x;
func(y);
}
在执行结束时, x
值为1
, y
为0
(如您所见 )。
请注意,为了示例,我使用0
作为空指针 ,但是如果您使用C ++ 11,则应该使用nullptr
(它没有重载的操作operaror<<
for std::ostream
)。
通过查看以下代码可以同化这个概念:
template<class Type> using ptr = Type*;
ptr<int>& x;
要么
std::unique_ptr<int>& x;
在这些示例中, x
是对类型( ptr<int>
然后是std::unique_ptr<int>
)的引用,它恰好是具有指针语义的指针/类( operator*
和operator->
)。
可以在指针中的const
限定符的位置上进行可能有趣的离题。 考虑这两个实例:
void func(const int*& ptr)
void func(int*const& ptr)
它们的含义是:
按照ptr
的上述类比,它们将是:
ptr<const int>&
ptr<int> const&
因此,第一个将无法在函数体中执行*ptr = 1
(因为int
是常量),但很乐意执行ptr = 0
。
第二个表现相反,允许*ptr = 1
(因为指向的int不是常数),而禁止ptr = 0
(因为指针是常量)。
当然,在以下情况下:
void func(const int*const& ptr)
在ptr
类比中它将是ptr<const int> const&
,它们都不被允许。
什么时候使用这个? 这样做是否明智?
像每个功能一样,当您需要它时,您会发现它的用处。 但是,作为一般概念,有些人在释放动态分配的资源后使用它来重置指针(我不推荐这个,见下文)。
我们来看这个例子:
free_my_int(int*& ptr) {
delete ptr;
ptr = nullptr;
}
int* x = new int(42);
free_my_int(x);
在执行结束时, x
将被正确释放,指针自动设置为nullptr
(空指针)。 这样做是为了防止由于缺少ptr = nullptr
而导致的丑陋的分段错误或“未释放指针”错误消息。
但是使用C ++ 11和C ++ 14时,很少使用指针,甚至更少使用指针。 大多数用于指针的指针都没有被其他标准构造替换(例如,参见std::optional
, std::unique_ptr
, std::shared_ptr
或std::reference_wrapper
)。
让我们比较所有三个选项:
void func(type* param); // 'param' is a 'type*' variable
void func(type& param); // 'param' is a reference to a 'type' variable
void func(type*& param); // 'param' is a reference to a 'type*' variable
void func(type* param)
{
type x;
...
param = &x;
// Argument 'param' is regarded as a local variable in this function,
// so setting 'param = ...' will have no effect outside this function
}
当然,如果你做的*param = ...
,那么它会影响由指向的内存中的内容param
。 你也可以做param[5] = ...
例如,并影响该内存空间中的其他区域。
void func(type& param)
{
type x;
...
param = x;
// Argument 'param' is regarded as a reference to a variable outside this
// function, so setting 'param = ...' will effect the referenced variable
}
在这里,您只会更改引用的变量本身 ,因此它比将函数声明为void func(type* param)
更安全,然后通过调用func(¶m)
传递type param
的地址。
void func(type*& param)
{
type x;
...
param = &x;
// Argument 'param' is regarded as a reference to a variable outside this
// function, so setting 'param = ...' will effect the referenced variable
}
这类似于将函数声明为void func(type** param)
,然后通过调用func(¶m)
传递type* param
的地址,但同样,由于上述相同的原因,它更安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.