Jakob Bieling wrote:
> Joe Van Dyk <> wrote:
>
>>#include <queue>
>>#include <string>
>>#include <iostream>
>>
>>using namespace std;
>>
>>class Foo
>>{
>> public:
>> string data;
>>};
>>
>>class Holder
>>{
>> public:
>> void add_to_queue()
>> {
>> Foo f;
>> f.data = "Sup!";
>> holder.push(f); // Bad?
>> }
>> queue<Foo> holder;
>>};
>>
>>int main()
>>{
>> Holder h;
>> h.add_to_queue();
>> h.add_to_queue();
>> return 0;
>>}
>>
>>When I create a Foo object inside Holder::add_to_queue(), that's a
>>temporary variable. And then when I add it to the queue, isn't that
>>bad? Or does the push create a new copy of the Foo object and stick
>>that inside the queue?
>
>
> The latter. Your code is fine the way it is.
>
>
>>(wondering if I should use pointers or references instead of objects)
>
>
> If your actual code is very similar to the example code above, I see
> no reason for using pointers or references. When passing a Holder or a
> Foo object around, you might want to do that by const-reference (this is
> how you pass the temporary Foo to queue<Foo>:
ush, for example).
>
> hth
Thanks.
In actuality, Holder::add_to_queue takes a string and creates a Foo
object based on that string. Then that Foo object gets pushed into the
queue.
Let's rename Foo to BaseMessage.
So, I have several classes that inherit from BaseMessage. So,
JoesMessage, JimsMessage, etc. The contents of the String that gets
passed to Holder::add_to_queue needs to be examined somehow and the
appropriate object needs to be constructed and inserted into the Queue
(ideas welcome on an elegant way to do that).
In that case, the queue would need to contain pointers to BaseMessage
objects, right? As there would be JoesMessages, JimMessages, etc all in
the same queue.