On some Windows operating systems (primarily Windows 95, 98, and ME), GetOpenFileName() and GetSaveFileName() (and wrappers of these functions such as MFC’s CFileDialog) will permanently change the process’s current working directory unless the OFN_NOCHANGEDIR option is specified. As you can imagine, this can easily break your application if you ever rely on the current working directory being set to a particular value (such as if you open files using relative paths).
Of course, it is best to eliminate any such current working directory assumptions from your application completely.
This function will work most of the time, but every now and again it will run across a directory which it will claim isn’t one. Why?
The problem is caused because dwAtts is a bitfield (see the GetFileAttributes() documentation). Simple equality comparison isn’t appropriate, as if the directory has any other attributes (such as compressed, hidden, offline, etc.) the comparison will fail.
This is a style issue, so there is no right or wrong, but I suggest using a const reference for an input-only paramater to a C++ function and a pointer for an input/output or output-only parameter. This makes it slightly more obvious that the parameter might be modified by the function.
Example:
ReturnTypeFunction(constParamType&inputParam,ParamType*inputOutputParam,ParamType*outputParam){// ...
}voidUser(){ParamTypeinputParam;ParamTypeinputOutputParam;ParamTypeoutputParam;// Note the &s -- this is a bit of a warning something
// might happen to inputOutputParam or outputParam...
ReturnTyperet=Function(inputParam,&inputOutputParam,&outputParam);}
If my experience is typical, this is a very common construct:
ReturnTypeFunction(conststd::vector<T>&container){typedefstd::vector<T>::const_iteratoriterator_t;for(iterator_titer=container.begin();iter!=container.end();++iter){// Work with *iter
}}
The problem with this construct is that you have forced a container choice upon the user of your function. Slightly better, and basically your only choice when interoping with C, is this:
ReturnTypeFunction(T*array,intnumItems){for(inti=0;i<numItems;++i){// Work with array[numItems]
}// Or perhaps:
// for (T* pT = array; pT != array + numItems; ++pT) {
// Work with *pT
// }
}
With the above construct you can pass in any container which uses contiguous storage, such as an array or a std::vector (yes, std::vectorsare guaranteed to store the data contiguously). Passing a std::vector to the above function looks like:
I’ve seen the following STL construct countless times:
std::vector<T>container;for(inti=0;i<container.size();++i){// Work with container[i]
}
Unless otherwise necessary, it is better to use an STL iterator because it enables you to more easily change the underlying container. You can isolate the code changes required to one line by using typedef, as in:
typedefstd::vector<T>container_t;container_tcontainer;// Or ::const_iterator as necessary
for(container_t::iteratoriter=container.begin();iter!=container.end();++iter){// Work with *iter
}
Note that I wrote iter != container.end() as opposed to iter < container.end(). The former only requires an input iterator, while the latter requires a random access iterator—a more complicated iterator type supported by fewer STL containers.
I ran into problem today relating to Excel interop. A coworker made a change to a C# application I wrote and was trying to build it. The program relied on a project which had a reference to the Microsoft Excel 9.0 Object Library which ships with Office 2000. However, the coworker had Office 2003 installed which includes the Excel 11.0 Object Library and not the Excel 9.0 Object Library. Because of this, he could not build the application.
This is part 5/5 of my Deterministic Finalization and IDisposable post series.
This is the final example in my series on deterministic finalization in garbage-collected languages and the true motive behind the series: AutoReleaseComObject. The idea behind AutoReleaseComObject is simple: it is nothing but a wrapper around a COM object which calls Marshal.ReleaseComObject() upon Dispose() until the COM object’s reference count is 0 and the object is freed. Here’s the implementation:
This is part 4/5 of my Deterministic Finalization and IDisposable post series.
I guess my definition of tomorrow is much longer than I thought, but here’s another useful IDisposable class which I shall present without comment: AutoDeleteFile.
usingSystem;usingSystem.Diagnostics;usingSystem.IO;/// <summary>/// A file wrapper which automatically deletes the file unless Disarm()/// is called./// </summary>publicsealedclassAutoDeleteFile:IDisposable{privateFileInfom_underlyingFile;privateboolm_armed=true;privateboolm_disposed=false;publicAutoDeleteFile(FileInfounderlyingFile){Debug.Assert(underlyingFile!=null);m_underlyingFile=underlyingFile;}~AutoDeleteFile(){Dispose(false);}publicFileInfoFile{get{returnm_underlyingFile;}}publicvoidDisarm(){m_armed=false;}#regionIDisposableMemberspublicvoidDispose(){Dispose(true);GC.SuppressFinalize(this);}#endregionprivatevoidDispose(booldisposing){if(!m_disposed){if(m_armed){try{m_underlyingFile.Delete();}catch(Exception){// If we can't delete, oh well!}}m_disposed=true;}}}
This is part 3/5 of my Deterministic Finalization and IDisposable post series.
For the first example of a useful custom class which implements IDisposable, I will simply link to and reproduce Ian Griffith’s TimedLock — an enhancement of the C# lock statement which allows the specification of a timeout period instead of blocking forever while trying to obtain the lock.
The code for TimedLock is reproduced below:
usingSystem;usingSystem.Threading;// Thanks to Eric Gunnerson for recommending this be a struct rather// than a class -- avoids a heap allocation.// Thanks to Change Gillespie and Jocelyn Coulmance for pointing out// the bugs that then crept in when I changed it to use struct...// Thanks to John Sands for providing the necessary incentive to make// me invent a way of using a struct in both release and debug builds// without losing the debug leak tracking.publicstructTimedLock:IDisposable{publicstaticTimedLockLock(objecto){returnLock(o,TimeSpan.FromSeconds(10));}publicstaticTimedLockLock(objecto,TimeSpantimeout){TimedLocktl=newTimedLock(o);if(!Monitor.TryEnter(o,timeout)){#ifDEBUGSystem.GC.SuppressFinalize(tl.leakDetector);#endifthrownewLockTimeoutException();}returntl;}privateTimedLock(objecto){target=o;#ifDEBUGleakDetector=newSentinel();#endif}privateobjecttarget;publicvoidDispose(){Monitor.Exit(target);// It's a bad error if someone forgets to call Dispose,// so in Debug builds, we put a finalizer in to detect// the error. If Dispose is called, we suppress the// finalizer.#ifDEBUGGC.SuppressFinalize(leakDetector);#endif}#ifDEBUG// (In Debug mode, we make it a class so that we can add a finalizer// in order to detect when the object is not freed.)privateclassSentinel{~Sentinel(){// If this finalizer runs, someone somewhere failed to// call Dispose, which means we've failed to leave// a monitor!System.Diagnostics.Debug.Fail("Undisposed lock");}}privateSentinelleakDetector;#endif}publicclassLockTimeoutException:ApplicationException{publicLockTimeoutException():base("Timeout waiting for lock"){}}
It is trivial to use TimedLock instead of lock in your applications. Simply change statements from: