Regardless, I think lifetime annotations would solve far more problems than std::box. I really do like box as a suggestion as it would help clean up types, make things a bit more explicit in a few places, but there are bigger issues with C++ right now. This is a great suggestion (as is unique_resource for similar on the stack), but a relatively minor thing in the scheme of things. Still nice.
It isn't as if Microsoft, Apple and Google haven't been doing it for a while.
https://devblogs.microsoft.com/cppblog/high-confidence-lifet...
Which one of these (which implement the same copy/move semantics) would you prefer?
struct A {
box<int> thing;
}
struct B {
std::unique_ptr<int> thing;
B(std::unique_ptr<int> t) :
thing(std::move(t))
{}
B(const B& other) :
thing{std::make_unique<int>(*other.thing)}
{}
B& operator=(const B& other) {
thing = std::make_unique<int>(*other.thing);
return *this;
}
B(B&&) = default;
B& operator=(B&&) = default;
~B() = default;
};But you might want to allow a copy operation that recreates the entire structure. The proposed box<T> offers exactly the desired copy/move semantics.
For a self-referential type like a graph, either a value of the graph is completely stored in a contiguous region of memory, including all nodes, when the self-references should not be pointers, but offsets from the start of the region, and a graph value can be moved or copied anywhere without problems, or else a graph value consists only of a list of pointers, which point to node contents without pointers, which are scattered through the memory. In the second case, a graph value, i.e. the list of pointers, can also be copied or moved anywhere in the memory without any problems, like you would do with any single pointer.
Mixing pointers with data makes sense only for objects with embedded pointers whose purpose is to allow them to be inserted in linked links or trees, where such objects will never be copied or moved, but only created and destroyed.