【问题标题】:What is the scope of a C++ class added to a QList添加到 QList 的 C++ 类的范围是什么
【发布时间】:2015-09-21 11:02:16
【问题描述】:

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

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++ 的基础!
  • 除了“安全”之外是什么意思?
  • 猜我是笨蛋。在按照 Ulrich 的建议添加复制构造函数之后,很容易看到发生了什么。
  • “我有一个 QList 存储对象而不是指向这些对象的指针。”无论如何,这就是你经常使用QList 的方式:) 你到底有什么问题?为什么你认为这是一种不好的做法?

标签: c++ qt qlist


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2014-11-15
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多