Is there a way to automatically call a function when a class created by a new

I need to call a function whenever a class is created using new. Currently I need to write something like this:

MyClass *myClassPointer = new MyClass(...);
myFunction(myClassPointer);

When MyClass is created as a local object, myFunction cannot be called. MyClass has 2 constructors with different arguments. Is there a way to automate it that other programmers did not need to call it.

I work with a rather old structure, and myFunction is used for maintenance without breaking it.

edited

myFunction is a function of an open participant in the main application window, a witch is visible in the entire application code. But myFunction my will be migrated from the mainWindow class and will be replaced with a global function, if necessary.

I was thinking of some kind of macro in the myClass header file, because I do not need to check all the code already written and add these changes. But I could not find a solution.

Thanks in advance for any ideas or suggestions.

After acceptance.

The problem is due to the poor design of MyClass and its use in the framework. I accepted Mark's answer because MyClass must have been created by ClassFactory from the start.

+3
source share
2 answers

Use the factory class, not call newdirectly. factory may call myFunctionbefore returning a pointer.

+8
source

The factory object function is one of the possible solutions, but it makes it difficult and time-consuming to define derived classes: while simple, very very intrusive.

, - :

#define MYNEW( Type, args ) myFunction( new Type args )

myFunction arg. :

MyClass* myClassPointer = MYNEW( Type,( blah, blah, blah ) );

, , .

- , , new , MYNEW. , , new, , . ( " ", , "" ).

:

#include <stddef.h>

// Support machinery:
template< class Type >
Type* myFunction( Type* p ) { return p; }

enum NewCallObfuscation {};
#define MY_NEW( Type, args )    \
    myFunction( new((NewCallObfuscation*)0) Type args )

// Usage:    
struct MyClass
{
    void* operator new( size_t size, NewCallObfuscation* )
    {
        return ::operator new( size );
    }

    MyClass( int, int, int ) {}
};

int main()
{
    //MyClass* p = new MyClass( 1, 2, 3 );      //!Nyet
    MyClass* p = MY_NEW( MyClass,( 1, 2, 3 ) );
}

, , new, . , , , . ., .

hth.,

+3

All Articles