简体   繁体   English

推回向量

[英]push_back to a Vector

I have a weird problem. 我有一个奇怪的问题。 I have a vector that I would like to push objects on to like so: 我有一个向量,我想将对象推到这样:

vector<DEMData>* dems = new vector<DEMData>();
DEMData* demData = new DEMData();
// Build DEMDATA

dems->push_back(*demData);

There will be a few hundred DEMData objects in the vector. 向量中将有数百个DEMData对象。 The problem is when this code is finished, all items are equal to the last item "pushed back" to the vector? 问题是此代码完成后,所有项目都等于“推回”向量的最后一个项目吗?

Why are the other objects being overridden in the vector? 为什么其他对象在向量中被覆盖?

edit: 编辑:

The DemData class is simple, just a data structure with setters and getters: DemData类很简单,只是一个带有setter和getter的数据结构:

    class DEMData
{
private:
    int bitFldPos;
    int bytFldPos;
    const char* byteOrder;
    const char* desS;
    const char* engUnit;
    const char* oTag;
    const char* valType;
    int index;
public:
    void SetIndex(int index);
    int GetIndex() const;
    void SetValType(const char* valType);
    const char* GetValType() const;
    void SetOTag(const char* oTag);
    const char* GetOTag() const;
    void SetEngUnit(const char* engUnit);
    const char* GetEngUnit() const;
    void SetDesS(const char* desS);
    const char* GetDesS() const;
    void SetByteOrder(const char* byteOrder);
    const char* GetByteOrder() const;
    void SetBytFldPos(int bytFldPos);
    int GetBytFldPos() const;
    void SetBitFldPos(int bitFldPos);
    int GetBitFldPos() const;
    friend std::ostream &operator<<(std::ostream &stream, DEMData d);
};

EDIT: 编辑:

I am reading an XML file and building DEMData objects based on the attributes of each xml element: 我正在读取XML文件,并根据每个xml元素的属性构建DEMData对象:

DEMData demData;
  for (i = 0; attr[i]; i += 2)
  {
      if(strcmp(attr[i],"BitFldPos") == 0)
      {
      demData.SetBitFldPos(*attr[i + 1] - '0');
      }
      else if(strcmp(attr[i],"BytFldPos") == 0)
      {
        char* pEnd;
        int tmp = strtol(attr[i + 1],&pEnd,10);
        demData.SetBytFldPos(tmp);
      }
      else if(strcmp(attr[i],"ByteOrder") == 0)
      {
        demData.SetByteOrder(attr[i + 1]);
      }
      else if(strcmp(attr[i],"DesS") == 0)
      {
      demData.SetDesS(attr[i + 1]);
      }
      else if(strcmp(attr[i],"EngUnit") == 0)
      {
        demData.SetEngUnit(attr[i + 1]);
      }
      else if(strcmp(attr[i],"OTag") == 0)
      {
        demData.SetOTag(attr[i + 1]);
      }
      else if(strcmp(attr[i],"ValTyp") == 0)
      {
        demData.SetValType(attr[i + 1]);
      }
      else if(strcmp(attr[i],"idx") == 0)
      {
        char* pEnd;
        int tmp = strtol(attr[i + 1],&pEnd,10);
        demData.SetIndex(tmp);
      }
      //printf(" %s='%s'", attr[i], attr[i + 1]);
  }


  // Insert the data in the vector.
  dems.push_back(demData);

Why are you allocating the vector with new? 为什么要分配带有new的向量? Why are you allocating your temporary DEMData object with new? 为什么要用new分配临时DEMData对象?

A vector stores a copy of what you pass to it, not that data itself, so unless you're deleting the DEMData object you allocated with new, you're leaking memory ever time you push an item onto the vector. vector存储传递给它的内容的副本 ,而不是数据本身,因此,除非您删除使用new分配的DEMData对象,否则每当将项目推入向量时,都会泄漏内存。 Likewise, you're setting yourself up for memory leak problems by allocating the vector dynamically. 同样,通过动态分配向量来设置内存泄漏问题。

As to why the objects in the vector all seem to contain the same data, chances are pretty good that you have more of the same -- probably use of pointers combined with an incorrect copy ctor that ends up doing shallow copies a few places it shouldn't -- but since you haven't shown us that code, that's only a guess. 至于为什么向量中的所有对象似乎都包含相同的数据,您很有可能拥有更多的相同数据-可能是结合使用了指针和不正确的复制ctor,最终导致在不应该复制的几个位置进行浅复制不是-但是由于您没有向我们展示该代码,所以这只是一个猜测。

Edit: Now that you've added the code for your DEMData class, it looks very much like the guess above was correct -- you have pointers and no user-defined copy ctor, so you're getting a shallow copy. 编辑:现在,您已经为DEMData类添加了代码,看起来非常像上面的猜测是正确的-您具有指针并且没有用户定义的副本ctor,因此您得到的是浅表副本。

As a first step, I'd get rid of all the pointer char members, and replace them with std::string s. 第一步,我将摆脱所有指针char成员,并用std::string替换它们。 The int members should be all right -- copying them will copy the values. int成员应该没问题-复制它们将复制值。

Edit2: Given what you're doing with these member variables, it looks a lot like you should consider using two std::map s -- one for the std::string variables, and one for the int variables. Edit2:鉴于您正在使用这些成员变量,看起来很像您应该考虑使用两个std::map s-一个用于std::string变量,另一个用于int变量。

Please note that your vector holds not references to the objects, but their copies . 请注意,向量不包含对对象的引用,而是对对象的副本 This means that after you store a newly-created instance of DEMData in your vector, and update the object, the corresponding entry in the vector won't be updated. 这意味着在将新创建的DEMData实例DEMData在向量中并更新对象之后,向量中的相应条目将不会更新。

You need to make your vector store DEMData* , and push_back a pointer, not a value pointed to. 您需要使向量存储DEMData* ,并push_back一个指针,而不是指向的值。

I suppose the strings in the objects are the same. 我想对象中的字符串是相同的。 Presumably you use the same demData object to populate the vector. 大概您使用相同的demData对象来填充向量。

And since you use default copy constructor all copies contain the same (char*) pointers. 并且由于您使用默认的副本构造函数,因此所有副本都包含相同的(char *)指针。 Should you change the content of the memory referred by these pointers, all copies 'see' the changes. 如果您更改这些指针引用的内存内容,则所有副本都“看到”更改。

Your DEMData class needs a copy constructor and destructor in order to manage the strings' memory. 您的DEMData类需要复制构造函数和析构函数才能管理字符串的内存。 As it stands what (probably) is happening is that a DEMData object is created, inserted into the vector which creates a new instance of DEMData with the same pointer values. DEMData目前情况(可能)发生的是,创建了一个DEMData对象,将其插入向量中,该向量将创建一个具有相同指针值的DEMData新实例。 Then you destroy the original DEMData (since there is no destructor) which leaves the pointers in the vector dangling. 然后,销毁原始的DEMData (因为没有析构函数),从而使指针悬空在向量中。 Then when you create a new DEMData it gets the same memory locations (by chance) and in the end all the objects point at the same locations. 然后,当您创建新的DEMData它将获得相同的内存位置(偶然),最后所有对象都指向相同的位置。

I'm not sure if in this case it's anything to do with the vector itself... The way you're using pointers to the vector and demData (instead of allocating them on the stack) looks a bit suspicious. 我不确定在这种情况下是否与向量本身有关...您使用指向向量和demData指针(而不是在堆栈上分配它们)的方式看起来有点可疑。

I'd expect normal C++ code to look like this: 我希望普通的C ++代码看起来像这样:

vector<DEMData>* dems = new vector<DEMData>();
DEMData demData
// Build DEMDATA

dems->push_back(demData);
...
delete dems;

Can you paste the rest of your code? 您可以粘贴其余代码吗? or perhaps the loop that does the demData building? 还是demData建立的循环?

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

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