【问题标题】:C++ Am I adding and accessing my Vector correctly?C++ 我是否正确添加和访问我的向量?
【发布时间】:2013-06-29 19:25:32
【问题描述】:

我正在创建一个对象并将其添加到 std::vector,然后访问 std::vector 以使用我放置在其中的对象的成员变量。

.h 包含std::vector

std::vector<Field *> vFields;
inline std::vector<Field *> getFields() { return vFields; };

在 .cpp 我这样做:

Field* f1 = Field::createWithLocation(ccp( p.x, p.y));
addChild(f1->getFieldSprite(), 2);
getFields().push_back(f1); // add the new field to a container
//vFields.push_back(f1); // add the new field to a container

std::cout << "add - # of Fields: " << getFields().size() << std::endl;

当实例化上面的Field* f1 时,会发生这种情况:

Field* Field::createWithLocation(cocos2d::CCPoint p)
{
    Field* f = new Field();
    //f->autorelease();
    f->initWithLocation(p);
    return f;
}

void Field::initWithLocation(cocos2d::CCPoint p)
{
    setFieldCenterPoint(p);
    setFieldGraphicName(FIELD::fieldIconFileName);

    setFieldSprite(cocos2d::CCSprite::create(getFieldGraphicName().c_str()));
     getFieldSprite()->setPosition(ccp(getFieldCenterPoint().x, getFieldCenterPoint().y));

    setFieldSize(getFieldSprite()->getContentSize());

    setFieldNumber(7159);

    setFieldTag(7159);

    std::cout << "When Field Created #: " << getFieldTag() << std::endl;
}

这很好用,当创建 Field 对象时,std::vector 在 size() 中显示 1 并且 getFieldTag() 像设置一样返回 7159

问题是当我从向量访问Field 时,发生了一些事情并且我崩溃了。我发现,如果我输出 getTagNumber() ,那就大不相同了。

访问向量的例子:

else if (getFieldLayerState() == kActive)
{
    // so did they click on a field?
    std::cout << "Field Layer Status Is Active" << std::endl;
    std::cout << "touch - # of Fields: " << vFields.size() << std::endl;

    // Loop through the field vector and get the size of each field and see if it was tapped    
    for (int f=0; f<vFields.size(); f++)
    {
        //field = (Field*) getFields().at(f);
        Field* field = (Field*) vFields.at(f);

        std::cout << "field #: "<< field->getFieldNumber() << std::endl;
        std::cout << "field tag: "<< field->getFieldTag() << std::endl;

        if (field->getFieldSprite()->boundingBox().containsPoint(location))
        {
            std::cout << "touched field #: "<< field->getFieldNumber() << std::endl;
            std::cout << "touched field tag: "<< field->getFieldTag() << std::endl;
            _dir->Instance()->getAudioEngine()->playBackgroundMusic("tap.mp3", false);    
        }
     }
}

cout 语句的示例输出:

When Field Created #: 7159
add - # of Fields: 1
Field Layer Status Is Active

touch - # of Fields: 1
field #: 1769234804
field tag: 353394533`

我在上面的if (field-&gt;getFieldSprite()-&gt;boundingBox().containsPoint(location)) 行崩溃了EXEC_BAD_ACCESS,很明显,向量中的内容与我放入的内容有所不同,或者看起来是这样。

谁能帮我理解我做错了什么?

【问题讨论】:

  • The rule of three 可能会有所帮助。
  • f1插入向量后,你会触摸它吗?这看起来好像有人释放了 Field 对象占用的内存。
  • 现在 f1 在创建后被放置在向量中,我只是从中访问片段,但是是的,我也会对其进行修改
  • 所以对于rule of three,您是说一个类应该始终实现自己的destructorcopy constructorcopy assignment operator 版本
  • 我的意思是你的代码是否包含delete f1 之类的东西,或者你是否从向量中删除了一些指针?顺便说一句,您不需要在这里进行类型转换:Field* field = (Field*) vFields.at(f);。如果您需要类型转换(Field*),那么它可能是错误的向量。

标签: c++ vector crash cocos2d-iphone cocos2d-x


【解决方案1】:

您的getFields 函数返回向量的副本。因此,对返回向量的任何更改都只会发生在副本中,而不会发生在原始向量中。

你想返回一个引用

std::vector<Field*>& getFields() { return vFields; }
//                 ^
// Note the ampersand

您可能还想添加函数的 const 重载:

const std::vector<Field*>& getFields() const { return vFields; }
// ^                                      ^
// Note the two `const` modifiers, the last one is important

然后,如果您修改向量,例如通过添加它,编译器将选择第一个非常量重载。如果你不修改向量,例如当您在向量上调用size 时,编译器将选择第二个 const 重载。

【讨论】:

  • 是所有getset 的情况,比如整数、字符串等吗?
  • 但是如果我直接使用向量而不使用 getter 就像:Field* field = (Field*) vFields.at(f); 我在上面的 for 循环中进行了编辑以显示它,仍然会发生
  • @Jason 这取决于。如果你有单独的 setter 和 getter 函数,那么你不应该返回引用。但是在这种情况下,由于您修改了向量,因此您需要返回一个引用。
  • @JoachimPileborg 一个很好的观点。而且我不明白 getFields().size() 是如何变成 1 的(或者输出与代码不对应)。但是,返回副本应该只在修改向量时失败,它不应该导致向量本身的数据不正确?
  • @Jason 只是因为您将项目添加到向量的副本中。语句完成后,该副本被破坏,下一次调用 getFields 返回一个全新的副本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 2015-12-03
  • 2022-11-17
  • 2010-10-17
  • 2012-05-27
相关资源
最近更新 更多