c++ - 添加到 QList 的 C++ 类的范围是什么

标签 c++ qt qlist

我写了一小段代码来向自己证明一些不好的做法确实是不好的做法。但是我没有看到我预期的结果。 我有一个 QList 存储对象而不是指向这些对象的指针。 这是类(class):

class test{
  public:
  test(int value){val=value; printf("created test %d\n",val);}
  ~test(){ printf("deleting test %d\n", val); val=0;}
  void print(){printf("test %d!\n", val);}
  int val;
};

我有一个带有测试功能的列表如下:

class myclass {
...
QList<test> _test_list;
void do_test_init();
void do_test();
...
};

void myclass::do_test_init()
{
  for(int i=0; i < 10; i++)
    _test_list.append(test(i+100));
}

void myclass::do_test()
{
  for(int i=0; i < 10; i++)
    _test_list[i].print();    
}

我看到的输出是:

created test 100
deleting test 100
created test 101
deleting test 101
created test 102
deleting test 102
created test 103
deleting test 103
created test 104
deleting test 104
created test 105
deleting test 105
created test 106
deleting test 106
created test 107
deleting test 107
created test 108
deleting test 108
created test 109
deleting test 109
test 100!
test 101!
test 102!
test 103!
test 104!
test 105!
test 106!
test 107!
test 108!
test 109!

我假设这是因为 append 函数正在获取我传入的对象的拷贝。这是否意味着以这种方式使用 QList 是安全的?我更喜欢存储指针而不是对象,这是误导了吗?

最佳答案

这个问题的答案是它是完全“安全”的,因为对象在附加到列表时被复制。提供复制构造函数清楚地表明了这一点。 清除列表时,复制的对象将被删除。

关于c++ - 添加到 QList 的 C++ 类的范围是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693568/

相关文章:

C++ Fstream 替换特定行?

javascript - QT/Javascript 桥 : Pass a Qlist<QVariantMap>?

c++ - 访问 QList 和 QSharedPointer 中引用的元素

c++ - 用于 C/C++ 开发的 Mac 与 Ubuntu?

c++ - 如何使用 opencv 中的 UpdateMotionhistory 函数修复此错误?

c++ - 设置精度在分配的数字之前的小数点后给出零

Qt/PyQt : How do I act on QWebView/QWebPage's "Open in New Window" action?

c++ - 控制台输出在Qt5中无法正确显示

c++ - QTSDK 4.8.4 中 QIMAGE 功能的替代方案

c++ - 创建多个对象类型的 QList