Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C&x2B的范围是什么+;类添加到QList中_C++_Qt_Qlist - Fatal编程技术网

C++ C&x2B的范围是什么+;类添加到QList中

C++ C&x2B的范围是什么+;类添加到QList中,c++,qt,qlist,C++,Qt,Qlist,我写了一小段代码来向自己证明一些不好的做法确实是不好的做法。然而,我没有看到我预期的结果。 我有一个存储对象的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 %

我写了一小段代码来向自己证明一些不好的做法确实是不好的做法。然而,我没有看到我预期的结果。
我有一个存储对象的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();    
}

我假设这是因为append函数正在复制我传入的对象。这是否意味着以这种方式使用QList是安全的?我的偏好是存储指针而不是对象,这是错误的吗?

这个问题的答案是,当对象被添加到列表中时,它是完全“安全”的。提供一个复制构造函数可以清楚地显示这一点。
清除列表时,复制的对象将被删除。

为什么不安全?你只需要知道你在做什么。您附加到列表中的任何内容都将被复制,然后列表将“拥有”该对象。如果您想保留所列对象的所有权,只需在列表中放置指针即可。仅仅取决于你想做什么…请阅读所谓的“三定律”,这是C++的基础。“安全”是什么意思?我想我是在装傻。在按照Ulrich的建议添加了一个复制构造函数之后,很容易看到发生了什么。“我有一个存储对象的QList,而不是指向这些对象的指针。”这就是你在很多时候使用
QList
的方式:)你到底出了什么问题?你为什么认为这是个坏习惯?
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!