In my C++ application I sometimes create different output files for troubleshooting purposes. Each file is created at a different step of our pipelined operation and it's hard to know file came before which other one (file timestamps all show the same date).
I'm thinking of adding a global counter in my application, and a function (with multithreading protection) which increments and returns that global counter. Then I can use that counter as part of the filenames I create.
Is this considered bad practice? Many different modules need to create files and they're开发者_开发知识库 not necessarily connected to each other.
If it's only for debugging, is temporary, and will not be released you can do whatever is quickest and easiest.
If, on the other hand, it's something that's likely to stay in your application long term and possibly sneak into a release then I'd definitely take more time and write a basic file creation module that all your other modules have access to.
I think, adding to file name current system time with high enough precision will be cleaner and easier to implement and maintain
//helper function to encapsulate details
string makeFileName(string filename)
{ return filename + getCurrentTime(); }
void MyClass::SomeMethod()
{
File f = CreateFile(makeFileName("myclassfile"));
...
}
It's not bad practice in general.
In C++, I would write a singleton class that would contain the counter and the multithreaded protection. That would be cleaner and would avoid using global variables like you do in c (you would use class static variables instead).
I'd personally create a factory for these files that would be in charge of returning the file object. You can have that function (or class) have a static variable for the counter.
I've generally abandoned global variables of any kind in favor of static member variables. They perform the same function and you can restrict how the static members can be changed and accessed.
精彩评论