views:

32

answers:

1

I have some code which creates a synchronised queue which I use in a data gathering class to report it's data. The method which creates queues is kicking up a warning:

Queue^% DataGatherer::AddOutputQueue()
{
    Queue^ outputQueue = Queue::Synchronized(gcnew Queue);
    AddOutputQueue(outputQueue);
    return outputQueue;
}

1>.\DataGatherer.cpp(21) : warning C4172: returning address of local variable or temporary

Is this a warning I should be worried about or am I safe in this case and it's just the compiler getting confused about Queue::Synchronized returning a Queue^? The code appears to run fine, but warnings make me nervous ;-)

+1  A: 

Queue^% indicates a handle being passed by reference. However, the handle inside the func is a local variable which can't be passed by reference since it's potentially destroyed when the func finishes. Remove the % from the return type and you are fine.

Edit: It doesn't mean anything your code seems to work. It can stop doing so any minute.

Any idea how I can get the function to return a reference which both the DataGatherer class and the caller can use?I agree on the point about the fact it might not always work; that was most of the reason I asked the question :-)
Jon Cage
To return a reference, you need to create the object being referenced on the heap rather than on the stack. I don't see why you should do that though, in your code Queue^ is a handle which in a way is a reference.
Correct me if I'm wrong but isn't that what `gcnew Queue` does? AFAIU the syncronized bit just wraps the underlying class to make it threadsafe. At least, that was my intention...
Jon Cage
`gcnew Queue` creates an object on the heap, correct. `Queue^` is an object on the stack. That cannot be passed back by reference because it's on the stack.