Skip to main content
gamedev.net
🔒 Locked

Pointer problems

Started by Aidamina Mar 4, 2006 at 10:35 AM 8 replies 1.7k views
Original Post
Aidamina
Aidamina
Why doesnt this work? And what do i need todo to make this work

float test()
{
    return 0.1337;
}
void * Call()
{
    return (void *)&test();
}
-->My Site<--
ToohrVyk
ToohrVyk
Store the temporary value returned by the first function in a heap-allocated variable, and return it. The caller is responsible for deleting that memory.

float test() {  return 0.1337;}void* call() {  return new float(test());}


Check you favorite C++ manual for heap/stack allocation and temporary values.
Enigma
Enigma
void *? Yuck! What are you trying to achieve? There is a 99.9% chance that a better technique exists than void *s.

Σnigma
Aidamina
Aidamina
Well the think is that it should no only return float this was just an example, i want to return an object aswell so it should be some kind of universal pointer.
-->My Site<--
ToohrVyk
ToohrVyk
What for?

Also, how will you know what object it is?
Aidamina
Aidamina
Below is the implented code. ret in the call function has a correct value in the local scope but it should have a value when it returns aswell if RT is a pointer right?

	class ICallback 	{	public:		virtual void * Call()=0;	};	template<class C,typename RT>	class Callback  : public ICallback	{	private:		C*   m_pClass;		RT  (C::*m_pMethod)();			public:		Callback ()     		{ 			m_pClass = 0; 			return;			}		Callback (C* pClass, RT (C::*pMethod)())     		{ 			m_pClass = pClass; 			m_pMethod=pMethod;			return;			}		void SetClass(C* pClass)		{ 			m_pClass = pClass; 			return;		}		void SetMethod(RT (C::*pMethod)())		{			m_pMethod=pMethod;			return;		}						void * Call()		{			RT ret = (RT )((m_pClass->*m_pMethod)());				return &ret		}	};
-->My Site<--
ToohrVyk
ToohrVyk
Quote:
Original post by Aidamina
		void * Call()		{			RT ret = (RT )((m_pClass->*m_pMethod)());				return &ret		}


You return the address of a stack variable, which is destroyed when the function returns, so you return the address of an invalid variable.

Aidamina
Aidamina
Any suggestions?
Its supposed to be a callback with result;
Cant i just return the result directly and ifso how do i turn that into void *
Thank you
-->My Site<--
Zahlman
Zahlman
Is there a reason you can't also template the interface on return type?

template <typename RT>class ICallback {  public:  virtual RT Call()=0;;// I suppose this qualifies as a variation on the// "curiously recurring template pattern"template <class C,typename RT>class Callback : public ICallback<RT> {  // etc.


The C++ type system is stronger than that in C. You are advised not to fight it - it wants to help you, but will not turn down a fight.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.