Pointer problems

Started by
8 comments, last by Zahlman 18 years, 1 month ago
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<--
Advertisement
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.
void *? Yuck! What are you trying to achieve? There is a 99.9% chance that a better technique exists than void *s.

Σnigma
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<--
What for?

Also, how will you know what object it is?
the return value that holds the 0.1337 is destroyed, so what Call() returns is useless you need to store it in something permenant like ToohrVyk suggested, if you using c which what it looks like you can use malloc()
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<--
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.

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<--
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.

This topic is closed to new replies.

Advertisement