简体   繁体   English

C ++ Pass by value / reference

[英]C++ Pass by value/reference

I have the following code snippet: 我有以下代码片段:

vector<DEMData>* dems = new vector<DEMData>();
ConsumeXMLFile(dems);

if(!udp_open(2500))
{

}        

I want the ConsumeXMLFile method to populate the vector with DEMData objects built from reading an XML file. 我希望ConsumeXMLFile方法使用通过读取XML文件构建的DEMData对象填充向量。 When ConsumeXMLFile returns, the dems vector is empty. 当ConsumeXMLFile返回时,dems向量为空。 I think I'm running into a pass by value problem. 我想我遇到了价值问题。

通过这看起来ConsumeXMLFile采用指向向量的指针,所以我怀疑这是一个值传递值问题。

Are you at any point reassigning the pointer that is passed into the function? 你是否在任何时候重新分配传递给函数的指针? In other words, does your function look anything like this: 换句话说,你的功能看起来像这样:

void ConsumeXMLFile(vector<DEMData>* dems) 
{
   // ... some code ...

   dems = new vector<DEMData>();

   // ...more code...
}

This is a common mistake that I see beginning C++ programmers (and C programmers) make. 这是我看到C ++程序员(和C程序员)开始做的常见错误。 What is going on here is that a pointer to the dems vector is being passed by value , which means that if you modify the pointed-to vector, that will affect the the vector possessed by the caller. 这里发生的是指向dems向量的指针正在通过值传递 ,这意味着如果修改指向向量,则会影响调用者拥有的向量。 However if you modify the pointer (which is passed by value ) this will not affect the pointer possessed by the caller. 但是,如果修改指针 (由传递),则不会影响调用者拥有的指针。 After the re-assignment, the dems pointer in ConsumeXMLFile will point to a totally different vector than the dems pointer that the caller holds. 在重新赋值之后,ConsumeXMLFile中的dems指针将指向与调用者持有的dems指针完全不同的向量。

One of the things that makes me suspect that you might be doing this is that this is C++ and there's no clear reason why you would want to pass a pointer to the vector instead of a reference to the vector otherwise. 让我怀疑你可能会这样做的一件事是,这是C ++,并且没有明确的理由为什么你想要传递指向向量的指针而不是向量的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM