c++invariantspreconditionslifetime-scoping

C++ ensure object exists while executing a function


I have a function foo. During the execution of foo, I want to be certain that an object of type Bar exists. Let’s call whatever object that happens to be “bar.”

I cannot copy or move bar, and bar can have any storage duration. The one thing I do know about bar is that it is an empty object.

foo doesn't need to do anything with bar or know anything about it.

What are my options for ensuring bar exists during foo, and what are their strengths and limitations?


Solution

  • the calling environment could pass a dangling reference into foo

    It really couldn't. Dangling references are not legal, so the only way for this to happen is by the caller violating the language rules. I don't find this a compelling concern.

    pass a shared_ptr to bar in. But this would require bar to have dynamic storage duration.

    Not quite. A shared_ptr can be constructed with a custom deleter, so if the caller wants to pass in a "stack allocated" Bar, they can construct a shared_ptr with a deleter which does not delete anything.

    bar is that it is an empty object

    Then what's the point of the entire exercise? Is it because the Bar constructor and/or destructor have side effects which must occur before/after foo runs? If that's the case, maybe foo should just do those things itself, or a foo_wrapper function can be created to hide these details.