I have a class (A) that will own the memory for a set of instances of another class (B). A will store its instances of B as a set of std::unique_ptr<B>.
I want A to be able to return a reference to a set of raw pointers to those B objects, (i.e. I don't want any transfer of ownership). What is the best way to do this?
class A
{
private:
std::set<std::unique_ptr<B>> _Bs;
public:
std::set<B*>& getBs() { ???? };
}
I could create a new vector:
class A
{
private:
std::set<std::unique_ptr<B>> _Bs;
std::set<B*> _rawBs;
public:
std::set<B*>& getBs() { return _rawBs; };
}
std::set<B*>
A::A()
{
std::transform(_Bs.begin(),
_Bs.end(),
std::inserter(_rawBs, _rawBs.begin()),
[](auto uniq_ptr) { uniq_ptr.get(); }
}
But it seems a bit janky to store these pointers twice...
cosnt std::set<std::unique_ptr<B>> &? This isn't an ownership transfer.std::setofstd::unique_ptreven works. What does the comparison operator do?std::lessdoes for raw pointers.const &for the existing set. If the user wants a copy, they can make one themselves. As a side note, I don't even understand the usefulness of a set here...