Method return issue.

I have a method inside a class that works fine, but someone told me that there are two ways that I provide results and that AddString returns string + updates a_Data parameter. This is the code in my method:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
std::string* AddString(std::string* a_Data)
	{

		if (pointer_count.empty())
		{
			pointer_count.insert(std::pair<std::string*, int>(a_Data, 1));
			return a_Data;
		}
		else
		{
			std::string data = *a_Data;
			int count = 0;

			for (Map_Type::iterator iter = pointer_count.begin(); iter != pointer_count.end(); ++iter)
			{
				count++;
				if (data == *(iter->first))
				{
					a_Data = iter->first;
					++iter->second;
					break;
				}
                        }
				if (count == pointer_count.size())
				{
					pointer_count.insert(std::pair<std::string*, int>(a_Data, 1));
				}
		}return a_Data;
	}


This is how I call my method:
m_Data = g_StrMgr.AddString(m_Data);


Should I call it like this?
g_StrMgr.AddString(m_Data);
First, a_Data is not updated or rather a_Data is updated but it's just a local copy of a pointer, so the change isn't propagated to the calling code -- this is perfectly fine, if unnecessary. Second, it doesn't appear you actually want a map of std::string pointers or if ( data == *(iter->first)) wouldn't be in your code.

If you did actually want the map indexed on std::string*, the following would probably be just fine.

1
2
3
4
5
std::string* AddString( std::string* a_Data)
{
    pointer_counter[a_Data]++ ;
    return a_Data ;
}


Last edited on
Yea the purpose of the method is to compare the strings where the pointers point and then act accordingly.
But how do you think i should call the method? Is this uneccesary?
m_Data = g_StrMgr.AddString(m_Data);
Yea the purpose of the method is to compare the strings where the pointers point and then act accordingly.


Makes me suspicious there may be a design error, but hard to say without knowing what you're doing.

But how do you think i should call the method? Is this uneccesary?
m_Data = g_StrMgr.AddString(m_Data);


If your intention is to modify m_Data with the return value, yes. This is necesary.

g_StrMgr.AddString(m_Data); would not modify m_Data.
Thank you very much!
Topic archived. No new replies allowed.