Say I have a Box. It contains Things, which are made by the Box
, and only the Box
. The Things are also uncopyable.
There is also an ownership relation, so I'd like to use unique_ptr
s. (If the Box goes, everything goes with it.)
#include <memory>
#include <vector>
class Thing {
friend class Box;
public:
~Thing() {/* delete thing */};
private:
Thing() {/* construct thing */};
Thing(const Thing& other) = delete;
Thing& operator=(Thing&& other) = delete;
};
class Box {
private:
std::vector<std::unique_ptr<Thing> > contents{};
public:
void makeThing() {
contents.push_back(nullptr);
contents.back().reset(new Thing()); // I can live with the 'new' keyword here.
}
};
My question is: is it bad to add to the vector by pushing a nullptr
then resetting it to a new object? (Aside from the new
keyword, which seems fine if the constructor doesn't throw?)
Note: I have already seen alternative ways to overcome the private constructor and deleted copy semantics. But is there anything dangerously wrong with what I wrote above?
Note 2: Explicitly stating it here since it already caught a few people: std::make_unique
will not work as the Thing constructor is private.