简体   繁体   English

这样安全吗? (Qt QQueue.dequeue()C ++内联指针取消引用)

[英]is this safe? (qt QQueue.dequeue() c++ inline pointer dereference)

Object object = *(queue.dequeue());

queue is a QQueue<Object*>. queue是一个QQueue <Object *>。 i'm concerned that the dequeued pointer is deleted before i dereference it. 我担心在我取消引用它之前删除了出列指针。 of course i can access object 's data but that doesn't mean anything. 当然我可以访问object的数据,但这并不意味着什么。 doing it all in one line like this is convenient (i don't want a pointer because i want object to be deleted automatically when it goes out of scope) but if it's not safe then i can't do it. 像这样在一行中完成这一切很方便(我不想要指针,因为我希望在超出范围时自动删除object )但是如果它不安全则我不能这样做。 please advise. 请指教。 thanks. 谢谢。

It isn't immediately unsafe per se, but chances are you'll be using it wrong . 它本身并不是不安全的 ,但你可能会错误使用它

All your code does is make a copy of the element pointed to by the last element of queue . 您的所有代码都是为queue的最后一个元素指向的元素的副本 By dequeuing the element, you lose the pointer to it, and you now have no way of freeing that original object in case it was dynamically constructed. 通过使该元素出队,您将失去指向该元素的指针,现在您无法释放该原始对象,以防它是动态构造的。

Correct example (no dynamic objects, no leak): 正确的示例 (无动态对象,无泄漏):

QQueue<Foo*> q;

{
  Foo a;
  q.enqueue(&a);
  Foo b = *q.dequeue();
}

Broken example (dynamic object leaked): 破碎的例子 (动态对象泄露):

QQueue<Foo*> q;
q.enqueue(new Foo);   // eeew, naked "new" in C++...
Foo c = *q.dequeue();
// now the newed element is leaked

You're right that c is safely destroyed at the end of its scope, but you're leaking the orginal, new'ed object, to which you have no pointer or reference now. 你是对的, c在其范围的末尾被安全地销毁,但是你正在泄漏原始的,新的对象,你现在没有指针或引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM