How Can I Prevent Myself From Using a Parameter After I’ve Extracted All Value? -- Raymond Chen
Imagine you have a function parameter that you want to protect from direct access, ensuring that all future interactions occur through a wrapper or transformation. This situation often arises in scenarios like implementing a logging wrapper for a class. In this discussion, we'll explore a clever technique known as "hide_name" to achieve this goal, allowing you to enforce the use of the wrapper and prevent direct access to the parameter.
How Can I Prevent Myself From Using a Parameter After I’ve Extracted All Value From It?
By Raymond Chen
From the article:
Suppose you have a function that takes a parameter that you want to transform in some way, and you want to require that all future access to the parameter be done through the transformed version. One example is a wrapper class that does logging.¹
struct WidgetRefWrapper { WidgetRefWrapper( Widget& widget, Logger& logger) : m_widget(widget), m_logger(logger) {} void Toggle() try { m_logger.Log("Toggling the widget"); m_widget.Toggle(); m_logger.Log("Toggled the widget"); } catch (...) { m_logger.Log("Exception while toggling the widget"); throw; } private: Widget& m_widget; Logger& m_logger; }; void DoSomething(Widget& widget) { Logger& logger = GetCurrentLogger(); WidgetWrapper wrapper(widget, logger); // Do not use the widget directly! // Always use the wrapper! if (needs_toggling) { wrapper.Toggle(); } }You want that “Do not use the widget directly!” comment to have some teeth. Can you “poison” the
widget
parameter so it cannot be used any more?