在C ++中传递对指针的引用 [英] Passing references to pointers in C++

查看:107
本文介绍了在C ++中传递对指针的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,没有理由我不应该允许在C ++中传递一个指针的引用。然而,我这样做的努力是失败,我不知道为什么。

As far as I can tell, there's no reason I shouldn't be allowed to pass a reference to a pointer in C++. However, my attempts to do so are failing, and I have no idea why.

这是我在做什么:

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}

// sometime later 
{
    // ...
    string s;
    myfunc(&s);
    // ...
}


无法将参数1从'std :: string *'转换为'std :: string *&'

cannot convert parameter 1 from 'std::string *' to 'std::string *&'


推荐答案

您的函数期望引用调用范围中的实际字符串指针,而不是匿名字符串指针。因此:

Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:

string s;
string* _s = &s;
myfunc(_s);

应该编译正常。

,这只有在您打算修改传递给函数的指针时才有用。如果你打算修改字符串本身,你应该使用Sake建议的字符串引用。考虑到这一点,它应该更明显为什么编译器抱怨你的原始代码。在你的代码中,指针是在飞行中创建的,修改该指针将没有后果,这不是预期的。引用(与指针)的想法是引用总是指向一个实际的对象。

However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.

这篇关于在C ++中传递对指针的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆