@@ -21,15 +21,22 @@ namespace opencensus {
2121namespace context {
2222
2323// WithContext is a scoped object that sets the current Context to the given
24- // one, until the WithContext object is destroyed.
24+ // one, until the WithContext object is destroyed. If the condition is false, it
25+ // doesn't do anything.
2526//
26- // Because it changes the current (thread local) context, NEVER allocate a
27- // WithContext in one thread and deallocate in another. A simple way to ensure
28- // this is to only ever stack-allocate it.
27+ // Because WithContext changes the current (thread local) context, NEVER
28+ // allocate a WithContext in one thread and deallocate in another. A simple way
29+ // to ensure this is to only ever stack-allocate it.
30+ //
31+ // Example usage:
32+ // {
33+ // WithContext wc(op.ctx_);
34+ // // Do work.
35+ // }
2936class WithContext {
3037 public:
31- explicit WithContext (const Context& ctx);
32- explicit WithContext (Context&& ctx);
38+ explicit WithContext (const Context& ctx, bool cond = true );
39+ explicit WithContext (Context&& ctx, bool cond = true );
3340 ~WithContext ();
3441
3542 private:
@@ -39,10 +46,13 @@ class WithContext {
3946 WithContext& operator =(const WithContext&) = delete ;
4047 WithContext& operator =(WithContext&&) = delete ;
4148
49+ void ConditionalSwap ();
50+
4251 Context swapped_context_;
4352#ifndef NDEBUG
4453 const Context* original_context_;
4554#endif
55+ const bool cond_;
4656};
4757
4858} // namespace context
0 commit comments