In the olden C days, code like this was deemed expensive:
1 2 3 4
|
void foo1()
{
char str[128]; // allocated on the stack each time foo1() is called
}
|
So a better alternative is this:
1 2 3 4
|
void foo2()
{
static char str[128]; // allocated on the heap, once
}
|
The c++ version is like this:
1 2 3 4 5
|
class MyClass1
{
void foo3() { }
char m_str[128]; // allocated once per instance
};
|
which works well, until I start to multithread and two threads are accessing the same instance (race condition). Of course, I can use a mutex, etc... ...but then I have to design for deadlocks. All that is too much trouble just overkill for a temporary string.
So my question is, if I go back to a foo1() equivalent and do this:
1 2 3 4 5 6
|
class MyClass2
{
void foo4() {
char str[128]; // allocated once per call
}
};
|
is it going to be expensive? I am asking, in particular, in the case of gcc - I realize that compiler technology is improving all the time, so I'm just trying to get a handle of how gcc might handle these differences (hoping I don't have to go to a disassembler).
I call fooX() quite often and don't worry about replacing char str with std::string - I still have to deal with the same issue.
If it turns out that it's expensive, I may have to do this:
1 2 3 4 5
|
class MyClass3
{
void foo5( char* str ) { // allocated by caller, in this case, a thread
}
};
|
but I'm trying to avoid this if I can (too many args to fooX already).
Most likely, I will go with MyClass2 or MyClass3, but I'd like to hear some informed opinions on this issue. TIA.