为什么在C ++中我需要通过引用传递一个指针来改变指向的内容? [英] Why in C++ do I need to pass a pointer by reference to change the pointed content?

查看:207
本文介绍了为什么在C ++中我需要通过引用传递一个指针来改变指向的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个函数来从着色器代码文件加载文本。我偶然发现了一些关于指针的奇怪的事情,我不知道为什么。

I am writing a function to load text from shader code file. I have stumbled upon something strange regarding pointers and I cannot figure out why.

我有一个名为Load的函数。在此函数中,我在输出变量中复制文本流中的文本。

I have a function named Load. In this function I copy text, taken from a file stream, in the output variable.

static void Load(const GLchar* source_path,  GLchar* output,GLint& count )
{
    string code;

    // loading logic here
    code= vShaderStream.str(); // copying the string from the stream
    count = code.length(); 
    output = new GLchar[count];
    std::size_t length = code.copy(output, count, 0);
    output[length]= '\0';
}

p>

Load is called in this way:

for (size_t i = 0; i < d_n_fragment; i++)
{
    Load(d_fragment_source_path, d_fragment_code[i], d_fragment_string_count[i]);
} 

其中 d_fragment_code 是Glchar的双重指针* *已经初始化。调用Load函数后,指针 d_fragment_code [i] 不包含文本。我试图改变Load函数的签名:

where d_fragment_code is a double pointer of Glchar** which is already initialized. After Load function is called the pointer d_fragment_code[i] contains no text. I tried to change the signature of the Load function to:

static void Load(const GLchar* source_path,  GLchar*& output,GLint& count )

,从而通过引用传递指针。它工作,在函数调用 d_fragment_code 正确保存从文件加载的文本,但我不明白为什么指针,它将通过引用传递。

and thus passing the pointer by reference. It works, after the function is called d_fragment_code holds correctly the text loaded from the file but I don't understand why a pointer it is to be passed by reference.

我认为只传递一个指针就足以改变它的内容。我很困惑,你能谈谈一些光吗?

I thought that passing a pointer only would suffice to change its content. I am confused, could you shed some light on it?

推荐答案

如果你必须修改指针而不是指针指向的对象。

You should pass pointers by reference if you have to modify the pointer rather than the object that the pointer is pointing to.

使用双指针也是一个类似的情况。

Using double pointers is also a similar case.

这里有一个更详细的文章:

http://www.codeproject.com/Articles/4894/Pointer-to-Pointer-and-Reference-to-Pointer

Here is a more detailed article:
http://www.codeproject.com/Articles/4894/Pointer-to-Pointer-and-Reference-to-Pointer

这篇关于为什么在C ++中我需要通过引用传递一个指针来改变指向的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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