A few pointers...on pointers

Started by
2 comments, last by gimp 23 years, 9 months ago
I know what I want to do but am still wrangling with the syntax... This sort of thing really should be elementary for me at this point... I have a struct thats has pointer to a string.
    
struct Message_t
{
	string			*Location;
	string			*Data;
};
[/source]

With that struct member I pass it in to a function that should be able to use the data, something along the lines as follows:

[source]
static CBaseMessage* Switch(Message_t message)
{
	blah=Registry.find(message->*Data);
...
    
If I left the * out I think I''d be doing the find on the pointer, which probably wont het the me the recors I''m looking for... gimp (You quit welcome to tell me to go back and reread my manual )
Chris Brodie
Advertisement
First, you have to compare apples to apples. That is, when you definied your map, what were your template types? If the key type is a string, then you''re ALMOST there.
Instead of:
message->*Data
you need:
*message->Data.

Think of it this way: (message->Data) is a pointer, so you want what it points to: *(message->Data). Turns out you don''t need the parenthesis with order of ops, so *message->Data is it.

However, if your template uses a const char* as the key, you need to convert the string to a c-type string using the c_str () function:
message->Data->c_str ()

Hope that helps.
Just a pointer...

You shouldn''t use -> access if you''re sending the function a struct, only if you''re sending a pointer to a struct.
A polar bear is a rectangular bear after a coordinate transform.
Ah, thanks Armitage. I didn''t notice that.

gimp, your function takes the argument "Message_t message". This would make it a pass-by-value call to the function. In other words, the contents of the message struct would be copied. Let me tell you why this is a very bad thing:

The problem is that you have non-flat members in your struct, i.e. data types (string) that have pointers in them pointing to some other allocated memory. The default copy constructor for a struct is just a binary copy (memcpy, if you will), meaning that the strings don''t know that they''ve been copied. The original strings and the copies of the strings would both point to the same place in memory. When the function finishes, the copied strings would be destroyed, freeing the memory that was still being used by the original strings . Now, the original strings are broken.

You should pass anything other than simple types (int, char, double) by reference. This either means passing a pointer or a reference as your parameter. This is more efficient (only 32 bits of memory is copied to the function as a pointer), and will make sure you don''t have the unexpected copying of objects that you saw above.

So your function should probably be:
static CBaseMessage* Switch (Message_t &message) // reference
{
blah = Registry.find (*message.Data);
}

This topic is closed to new replies.

Advertisement