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

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

queue is a 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. 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. please advise. thanks.

Answers


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. 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.


Need Your Help

Application in Android Market not compatible with device

android android-manifest google-play

I've upload my application to Android Market, but my developer's device is not compatible with it.

How to use hbm2ddl tool with Maven?

maven maven-3 hbm2ddl hibernate-tools

I would like to use the Hibernate3 plugin for Maven (developed by Codehaus) but according to the last release date (2009-01-21), it seems that it's not actively supported. I need to use the hbm2ddl...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.