I have the class MyObject
. All instances of it should be owned by a MyObjectSet
, and it should not be possible to construct it anywhere else. Inside MyObjectSet
, I use a std::vector<MyObject>
to store all instances in.
The problem is, that for std::vector<MyObject>
to work, the move constructor of MyObject
has to be public (it is not enough to add std::vector<MyObject>
as a friend of MyObject
).
class MyObject {
MyObject(int n);
friend class MyObjectSet;
public:
MyObject(MyObject&&) = default; // without this, it doesn't compile
};
class MyObjectSet {
std::vector<MyObject> MyObjects;
public:
MyObject& GetMyObject(int some_param);
};
But if I make it public, it would be possible to instantiate MyObject
from elsewhere.
void SomeUnrelatedFunc(MyObjectSet& set) {
MyObject m(std::move(set.GetMyObject(0))); // this shouldn't be possible
}
Is there any way to solve this problem?
It is possible to store pointers to MyObject
instances inside MyObjectSet
instead, but I'd like to avoid that, if possible.