C ++为什么双指针用于输出/返回函数参数? [英] C++ why double pointer for out/return function parameter?

查看:427
本文介绍了C ++为什么双指针用于输出/返回函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++比较陌生,并且在一个相当大的C ++项目上工作。我注意到一些函数,它们将双指针作为对象的参数,函数将在堆上实例化。示例:

I'm relatively new to C++ and working on a fairly large C++ project at work. I notice handfuls of functions that take double pointers as parameters for objects that the function will instantiate on the heap. Example:

int someFunc(MyClass** retObj) {
    *retObj = new MyClass();

    return 0;
}



我不知道为什么总是使用双指针,而不是只有一个指针?这是一个语义提示,它是一个out / return参数,还是有一个更技术的原因,我没有看到。

I'm just not sure why double pointers are always used, in this project, instead of just a single pointer? Is this mostly a semantic cue that it's an out/return parameter, or is there a more technical reason that I'm not seeing?

推荐答案

使用双指针模式,以便新分配的 MyClass 可以传递给调用者。例如

The double pointer pattern is used so that the newly allocated MyClass can be passed to the caller. For example

MyClass* pValue;
someFunc(&pValue);
// pValue now contains the newly allocated MyClass

通过C ++中的值传递。因此,单个指针的修改只能从 someFunc 中可见。

A single pointer is insufficient here because parameters are passed by value in C++. So the modification of the single pointer would only be visible from within someFunc.

注意:使用C ++时,应考虑在此场景中使用引用。

Note: When using C++ you should consider using a reference in this scenario.

int someFunc(MyClass*& retObj) {
  retObj = new MyClass();
  return 0;
}

MyClass* pValue;
someFunc(pValue);

这允许您通过引用传递参数,而不是按值。因此,结果对调用者可见。

This allows you to pass the argument by reference instead of by value. Hence the results are visible to the caller.

这篇关于C ++为什么双指针用于输出/返回函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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