Qt的foreach表达式需要一个深层拷贝? [英] Qt's foreach expression requires a deep copy?

查看:156
本文介绍了Qt的foreach表达式需要一个深层拷贝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Qt的foreach函数有点问题。我有一个类的短语,这是QList的子类。在〜短语中,我删除了所有GlossItem指针。

在遍历Phrase中的GlossItem指针时,我想使用Qt的foreach:

  //短语是指向Phrase对象的指针,
//是子类别QList< GlossItem *>
foreach(GlossItem * glossItem,* phrase)
{
// use glossItem
}

出于某种原因,foreach正在对短语执行深层复制(我知道这是因为它需要我实现复制构造函数)。但是,如果有一个短语的副本 - 如果我不想创建每个GlossItem的深层副本 - 这意味着这些指针将被删除两次。 (或删除一次,然后崩溃)所以我不得不使用这个,它的工作原理,但不那么漂亮。

  for (i);(< i = 0; i< phrase-> count(); i ++)
{
GlossItem * glossItem = phrase->
// use glossItem
}

有没有办法解决这个问题呢?

解决方案

来自文档


Qt在进入foreach循环时自动获取容器的一个副本。



由于foreach会创建一个容器的副本,因此使用该变量的非const引用不允许修改原始容器。 >

所以我认为你的具体用例 foreach 是不合适的,否则你最终用附加指针的 Phrase 的全新副本,而不是返回所需的实际原始 Phrase

I am having a bit of a problem with Qt's foreach function. I have a class Phrase, which is a subclass of QList. In ~Phrase I delete all of the GlossItem pointers.

In iterating through the GlossItem pointers in Phrase, I would like to use Qt's foreach:

    // phrase is a pointer to a Phrase object, 
    // which is a subclassed QList<GlossItem*>
    foreach( GlossItem *glossItem , *phrase )
    {
        // use glossItem
    }

For some reason foreach is performing a deep copy on Phrase (I know this because it required me to implement the copy constructor). But if there is a copy of Phrase -- and if I don't want to create a deep copy of each GlossItem -- that means that those pointers will be deleted twice. (Or, deleted once, and then crash.) So I have to use this, which works but is less pretty.

    for(int i=0; i<phrase->count(); i++ )
    {
        GlossItem *glossItem = phrase->at(i);
        // use glossItem
    }

Is there a way around this or do I just need to live with it?

解决方案

From the docs

Qt automatically takes a copy of the container when it enters a foreach loop.

and

Since foreach creates a copy of the container, using a non-const reference for the variable does not allow you to modify the original container.

So I think for your specific use case foreach isn't suitable otherwise you end up with a fresh copy of the Phrase with additional pointers, rather than returning the actual original Phrase that you want.

这篇关于Qt的foreach表达式需要一个深层拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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