queue<char> and memcpy()

A

Alex Vinokur

Is using memcpy() with queue<char> safe?

------ C++ code ------
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;

int main()
{
queue<char> qch;
char ach[100];

qch.push ('h');
qch.push ('e');
qch.push ('l');
qch.push ('l');
qch.push ('o');
qch.push (' ');
qch.push ('w');
qch.push ('o');
qch.push ('r');
qch.push ('l');
qch.push ('d');

memset (ach, 0, sizeof(ach));

memcpy (ach, &qch.front(), 5); // Is this safe?
cout << ach << endl;

qch.pop();
qch.pop();
qch.pop();
qch.pop();
qch.pop();
qch.pop();

memcpy (ach, &qch.front(), 5);
cout << ach << endl;

return 0;
}

----------------------

--- Output ---

hello
world

--------------


Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
 
D

Dietmar Kuehl

Alex said:
Is using memcpy() with queue<char> safe?

No: the default container underlying a 'std::queue<T>' is 'std::deque<T>'
which is not contiguous at all. Well, it may be contiguous if all
elements fit into on block but even this is not guaranteed as objects
are not rearranged when removing the from the front.
 
A

Alex Vinokur

Dietmar said:
No: the default container underlying a 'std::queue<T>' is 'std::deque<T>'
which is not contiguous at all. Well, it may be contiguous if all
elements fit into on block but even this is not guaranteed as objects
are not rearranged when removing the from the front.
[snip]

So, how to copy data chunks from queue<char> into char[] ?
One-to-one?

queue<char> qch;
char ach[100];

for (int i = 0; i < 5; i++)
{
char = qch.front();
qch.pop();
}

Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
 
P

peter koch

Alex said:
Dietmar said:
No: the default container underlying a 'std::queue<T>' is 'std::deque<T>'
which is not contiguous at all. Well, it may be contiguous if all
elements fit into on block but even this is not guaranteed as objects
are not rearranged when removing the from the front.
[snip]

So, how to copy data chunks from queue<char> into char[] ?
One-to-one?

Right. But you could wrap it in a function if you'd like to. You
know... memcpy is likely to copy one-to-one as well.

/Peter
queue<char> qch;
char ach[100];

for (int i = 0; i < 5; i++)
{
char = qch.front();
qch.pop();
}

Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,229
Latest member
GloryAngul

Latest Threads

Top