3 ms·
C++ does have ways to force heap allocation, but frankly it's just an antipattern. It's easier to reason about value semantics than reference semantics. If you
by Maxatar 2y ago
C++ does have ways to force heap allocation, but frankly it's just an antipattern.
It's easier to reason about value semantics than reference semantics. If you want a class with a stable address that is heap allocated, then do so by writing class that has a private field that is heap allocated, preferably managed by a unique_ptr. Then disable copy assignment and construction and make a judgement call if you want to support move assignment, construction.
In effect, the idea is to make this aspect of the type an implementation detail that the user doesn't need to concern themselves with. They just create an instance of the type, and the type deals with the ownership or ensuring that the address is pinned, or whatever other details are needed to make it work. And of course the type does this by delegating that work to unique_ptr or some other means of ownership.