Very easy question...std::string* to std::string

I have a
value is a void *, which is a std::string...

std::string *fooPtr = static_cast<std::string *>(value);

std::string newFoo = fooPtr->c_str();

keeps giving me an exception in a multithreaded environment....


how can i get a normal "std::string" from "std::string*" ???

Thanks.
closed account (S6k9GNh0)
What exception is it throwing?

http://codepad.org/HVjpiSUZ
Last edited on
It would be... std::string newFoo = *fooPtr;
I'm just not sure about std::string *fooPtr = static_cast<std::string *>(value);.
If you want the other conversion (std::string to std::string *), it's like this:
std::string * fooPtr = &newFoo;
Coming back to the original post - It is possible to have problems if you pass
pointers from one thread to the next - the first thread may finish before the second and things may go awry.
But, If the first thread ends, shouldn't every thread be ended first?
I mean, when Thread 1 ends, does it ends every other thread first?
For example this three threaded (main thread plus 2 others) example crashes because thread 2 closes so quickly (without the Sleep function):
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
30
31
32
33
34
35
36
37
38
39
40
//Thread 3
DWORD WINAPI ThreadProc3(LPVOID lpParameter)
{

    string *ps = static_cast<string*>(lpParameter);

    string as =  ps->c_str(); //crash site

    cout << as << endl;

    return 0;

}


//Thread 2
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{

    string lamestr("Hello World");
    
    HANDLE hThread;
    hThread = CreateThread(NULL,0,ThreadProc3,&lamestr,0, NULL);
    //Sleep(15000); //
    
    return 0;

}

Thread1 - Main Thread
int _tmain(int argc, _TCHAR* argv[])
{
	
    
    HANDLE hThread;
    hThread = CreateThread(NULL,0,ThreadProc2,0,0, NULL);
    Sleep (15000); //live long enough for something to happen.
    
return 0;
}
Better use "WaitForSingleObject", as far as you are using WinAPI, but then ok, anyways i'm not making Threaded apps... And if i was going to, i would use the new operator, and pass a explicitly casted pointer, as i don't know what static_cast does. I think i should study a bit more the castings.
Last edited on
closed account (S6k9GNh0)
static_cast, is the C++ way of ascertaining the pointer cast at compiled time.
it was cashing because other thread 2 closes quick! I fixed it...Thanks.
Topic archived. No new replies allowed.