MFC › 8. Debugging and Maintenance
Using Modern C++ in MFC Projects
Smart pointers, lambdas and the STL alongside MFC.
Explanation
MFC predates C++11, but it compiles with the current standard (use /std:c++17 or /std:c++20, and /permissive-). You can adopt modern C++ gradually around MFC. Practical guidance:
What mixes well
- STL containers and algorithms for your own data:
std::vector,std::map,std::sort,std::find_if, range-basedfor. KeepCStringfor text that goes to MFC/Win32 APIs; convert withstd::wstring(s.GetString())andCString(w.c_str()). - Smart pointers for everything except objects MFC owns or deletes: use
std::unique_ptrfor helpers, data and modal dialogs on the heap; usestd::shared_ptrfor shared data. - Lambdas and
std::functionfor callbacks and algorithm predicates; storestd::functionin your own tables. std::thread/std::async/std::atomicfor workers (still marshal results to the UI byPostMessage: Threads and Timers).std::filesystemreplacesCFileFind, path manipulation and temp-file code.nullptr,override,auto,enum class,constexpr,static_assertanywhere.
What does not mix
- Never
deleteor wrap in a smart pointer an object whose lifetime MFC manages:CFrameWnd,CView,CDocument, windows that calldelete thisinPostNcDestroy, controls owned by a dialog, theCWinAppobject. Aunique_ptrto one of them is a double delete. - Message maps (
ON_COMMAND, …) need plain member function pointers; lambdas cannot go there. Dispatch from the member function to a lambda/std::functionif you want. CObject-derived classes are not copyable/movable;std::vector<CMyDialog>won’t work: storestd::unique_ptr<CMyDialog>.- MFC collections (
CArray…) are not STL-compatible; convert or avoid. - Macro clashes:
<windows.h>definesmin/max: use#define NOMINMAX. - Exceptions: MFC throws
CException*(pointers,Delete()them); the STL throws objects. Catch both where the code can reach both. /permissive-may reveal old non-standard code; fix it rather than disabling.
Example
#define NOMINMAX
#include <afxwin.h>
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
// ---- conversions at the MFC boundary
inline std::wstring ToWide(const CString& s) { return std::wstring(s.GetString(), s.GetLength()); }
inline CString ToCString(const std::wstring& w) { return CString(w.c_str(), static_cast<int>(w.size())); }
inline std::string ToUtf8(const CString& s) { CW2A a(s, CP_UTF8); return std::string(a); }
// ---- a command table: std::function instead of a growing switch
class CommandTable {
std::map<UINT, std::function<void()>> m_handlers;
public:
void Add(UINT id, std::function<void()> fn) { m_handlers[id] = std::move(fn); }
bool Run(UINT id) const {
auto it = m_handlers.find(id);
if (it == m_handlers.end()) return false;
it->second();
return true;
}
};
// a modal dialog class held by unique_ptr (it is created and destroyed by you, not by MFC)
class CAboutDlg : public CDialog {
public:
enum { IDD = IDD_ABOUTBOX };
CAboutDlg() : CDialog(IDD) {}
};
inline void ShowAbout() {
auto dlg = std::make_unique<CAboutDlg>();
dlg->DoModal();
}
int _tmain() {
if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;
// STL + CString: sort names case-insensitively using a lambda
std::vector<CString> names{ _T("pear"), _T("Apple"), _T("fig") };
std::sort(names.begin(), names.end(),
[](const CString& a, const CString& b) { return a.CompareNoCase(b) < 0; });
for (const CString& n : names) std::wcout << (LPCTSTR)n << L" "; // Apple fig pear
std::wcout << L"\n";
auto it = std::find_if(names.begin(), names.end(), [](const CString& s) { return s.GetLength() == 3; });
std::wcout << (it != names.end() ? (LPCTSTR)*it : L"none") << L"\n"; // fig
// conversions
CString cs = _T("Hello");
std::wstring ws = ToWide(cs) + L", World";
CString back = ToCString(ws);
std::wcout << ws << L" | " << (LPCTSTR)back << L" | utf8 bytes " << ToUtf8(back).size() << L"\n";
// command table with lambdas
int clicks = 0;
CommandTable table;
table.Add(1001, [&clicks] { ++clicks; });
table.Add(1002, [&clicks] { clicks += 10; });
table.Run(1001); table.Run(1002); table.Run(1001);
std::wcout << L"clicks = " << clicks << L", unknown id handled: " << table.Run(9) << L"\n"; // 12, 0
// std::filesystem instead of CFileFind
namespace fs = std::filesystem;
fs::path tmp = fs::temp_directory_path() / L"mfc_modern_demo";
fs::create_directories(tmp);
for (const wchar_t* n : { L"a.txt", L"b.log" }) std::ofstream(tmp / n).put('x');
int txtCount = 0;
for (const auto& e : fs::directory_iterator(tmp))
if (e.path().extension() == L".txt") ++txtCount;
std::wcout << L".txt files: " << txtCount << L"\n";
fs::remove_all(tmp);
return 0;
}
Common pitfalls
std::unique_ptr<CView>ordelete pFrame;: double delete or crash at exit. If MFC creates it (document template,new CMyDlgmodeless withPostNcDestroy), MFC deletes it.- Lambda captured
thisin a callback that outlives the window: the lambda dangles after the window is destroyed. - Using
std::threadand then updating controls directly from it; see Threads and Timers. CStringis not astd::wstring: no implicit conversion either way. Forgetting the length argument with embedded NULs truncates text.- Compiling old MFC code at
/std:c++latestor with/permissive-can expose old bugs: enable them step by step. for (auto x : CArray): older MFC versions lackbegin()/end(); check your version, or use an index loop.- Don’t convert wholesale: rewriting working MFC code to STL for style alone adds risk. Apply modern C++ to new code and when you touch old code.
Legacy vs modern
This lesson is the bridge between the tracks: the legacy idioms (RAII, STL), the modern library (smart pointers, lambdas, std::filesystem) and the MFC framework meet here. Many teams keep MFC for the UI shell and put business logic in plain, standard C++ libraries with no MFC dependency, which makes it testable and reusable.
Exercises
1. Why can't you register a lambda directly in an MFC message map?
ON_COMMAND(id, fn) expands to a table entry holding a member function pointer of the class, which a lambda isn’t. Write a member function that calls the lambda or std::function.