wxEVT_BUILD_STARTING event

Discussion about CodeLite development process and patches
sdolim
CodeLite Veteran
Posts: 69
Joined: Fri Oct 24, 2008 10:29 pm
Contact:

Re: wxEVT_BUILD_STARTING event

Post by sdolim »

Eran is correct. The temporary value is destroyed at the end of the statement:

Code: Select all

event.SetClientData(&(proj->GetName()));
But this is before the statement that actually calls ProcessEvent() to send the event to the plugins. The temporary value has been freed by that point.

Also, using the address of a local variable is OK in this case since the event handling is synchronous: ProcessEvent() does not return till all receivers have processed the event.
asterisc
CodeLite Enthusiast
Posts: 12
Joined: Sat Dec 20, 2008 3:01 am
Contact:

Re: wxEVT_BUILD_STARTING event

Post by asterisc »

Why is this working?

Code: Select all

#include <iostream>
#include <string>

using namespace std;

string msg()
{
	string v = "10";
	return v;
}

void print( string *msg )
{
	cout << msg->c_str() << endl;
}

int main(int argc, char* argv[])
{
	print( &msg() );

	return 0;
}
There are exceptions described in C++ standard.

Maybe I didn't get the problem right, but it's sure that the temporary isn't "undefined" freed
sdolim
CodeLite Veteran
Posts: 69
Joined: Fri Oct 24, 2008 10:29 pm
Contact:

Re: wxEVT_BUILD_STARTING event

Post by sdolim »

In this case, the temporary that holds the return value of msg() stays in scope until the end of the statement, when print() has returned.

This is different from the event-sending case, where there are two separate statements:

Code: Select all

event.SetClientData(...);
ProcessEvent(event);
In that case, a temporary used in the first function call has gone out of scope before ProcessEvent() is called. But using a local variable instead ensures that the value stays in scope through the end of the function (or block) containing both statements.
User avatar
eranif
CodeLite Plugin
Posts: 6375
Joined: Wed Feb 06, 2008 9:29 pm
Genuine User: Yes
IDE Question: C++
Contact:

Re: wxEVT_BUILD_STARTING event

Post by eranif »

Here is a complete sample that show the problem:

Code: Select all

#include <iostream>
#include <string>

using namespace std;

struct event {
	void *d;
};

class cls {
public:	
	string s;
	
public:
	cls(){
		cout << "ctor" << endl;
	}
	
	~cls(){
		cout << "dtor" << endl;
	}
};

cls msg()
{
	cls c;
	c.s = "10";
	return c;
}

void print( event *e )
{
	cout << ((cls*)e->d)->s.c_str();
}

int main(int argc, char* argv[])
{
	event e;
	e.d = (void*)&msg();
	print( &e );
	return 0;
}
Running this code gives this output:
ctor
dtor
10
which means that print() was invoked with 'e' pointing to an invalid pointer.
The reason that it does not crash is just because that the memory was not reused again - pure luck

Eran
Make sure you have read the HOW TO POST thread
Post Reply