Automatic source code replacement
I'm looking for a tool, regex or other magic to do some heavy code replacements.
Ideally I would be able to replace all instances of the new
operator with a call to a function preserving the arguments.
What are my options?
Update:
Example:
ClassA* a = new ClassA<int>(1,2,3,4,new ClassB(1,2),"horrible");
Should transform to:
ClassA* a = FUNCTION(ClassA<int>(1,2,3,4,FUNCTION(ClassB(1,2)),"horrible"));
Where FUNCTION will do something like:
FUNCTION(...) Debug(new __VA_ARGS__, __FILE__)
A simple replace nearly does it well, it only lacks the last )
.
Update:
My initial thought was to use a macro to track some additional info like __FILE__
, store it in a std container and then call new. What will happen if the container calls new? How do I add __FILE__
inside an overloaded new?
You don't mention why you want to do this, but I do wonder whether overloading the new operator might be a better option for you.
Why would one replace default new and delete operators?
Edit
The following links might also be relevant:
overloading new and delete in c++
Overriding "new" and Logging data about the caller
Macro to replace C++ operator new
http://blogs.msdn.com/b/calvin_hsia/archive/2009/01/19/9341632.aspx
It seems like this is a problem many people have tackled before. Googling for overload|override new __line__ __file__
will throw up further possibilities.
Some of your more viable options:
If it is only a few files, you could simply go through them in an IDE and use CTRL+H to find and replace (Thank you Mark Garcia)
If it is many files, you could write a Perl script to find and replace regular expression (I suggest Perl only because I have found regular expressions to be very straightforward in it) This could be done in a single line actually
perl -p -i -e 's/oldstring/newstring/g' `find ./ -name *.cpp`
Running this from command line will replace all instances of oldstring with newstring in every .cpp file in the current directory. Honestly, this is probably the most straightforward way for many files if you are simply replacing all instances of 'new' with another single string. Although this situation is unlikely, but you can always change old string to be whatever you want (say 'new Object' replaced with createObject)
链接地址: http://www.djcxy.com/p/73046.html上一篇: C ++中的一个定义规则究竟是什么?
下一篇: 自动源代码替换