Let's say I have a library which has a Document
class. An instance of Document
can own several instances of Field
. Field
has multiple subclasses (for example IntegerField
and StringField
), and even the API user can subclass it and supply subclass instances to Document
(let's say the user is allowed to develop a custom type of data to store in a field).
I'd like to expose the Field
instances owned by Document
through an API in such a way that users can interact with them, but without transferring ownership.
What is the right way to do this?
I thought about:
- Exposing a
const std::unique_ptr<Field>&
reference - this feels quite ugly - Exposing a plain
Field*
pointer - this doesn't feel right because the user might be unsure whether he should delete the instance or not - Using
std::shared_ptr
instead - this feels bad because the ownership is not really shared
For example,
class Document {
private:
std::map<std::string, std::unique_ptr<Field> > fields;
// ...
public:
// ...
// How is this done properly?
const std::unique_ptr<Field> &field(const std::string &name) {
return fields[name];
}
}
I'm looking forward to your suggestions.
(I also welcome advice about alternative approaches like what @Fulvio suggested.)