假设class Owner
有Member member
,其const
所有者的指针也必须const
。该指针被赋予member
构造函数中的Owner
,该构造函数接受指向成分member
的指针作为参数。
考虑Owner
的构造函数:
using namespace std;
class Owner;
class Member {
friend class Owner;
private:
// this object needs to know its owner for whatever reason
void setOwnership(const Owner* o){
if(owner != nullptr){
throw logic_error("Already owned.");
}
owner = o;
}
const Owner* owner;
};
class Owner {
public:
Owner(Member* m)
: member(move(m))
{
m->setOwnership(this);
}
// need to define copy ctor, move ctor, copy assignment, move assignment, destructor
// because we own member
protected:
const Member* const member;
};
现在我希望unique_ptr
为我处理member
的所有权,所以我试试
class Owner {
public:
// ATTEMPT 1
Owner(unique_ptr<Member> m)
: member(move(m))
{
member->setOwnership(this); // this doesn't work because member points to a const
}
// ATTEMPT 2
Owner(unique_ptr<Member> m){
m->setOwnership(this);
member = move(m); // this doesn't work because member is const
}
protected:
const unique_ptr<const Member> member;
};
Owner
构造函数的两次尝试都无法编译。我该怎么做呢?原则上似乎没有理由说我为什么不能这样做。
为了方便使用const
,我是否必须牺牲其中一个unique_ptr
?
答案 0 :(得分:3)
委托构造函数进行救援:
class Owner {
public:
Owner(std::unique_ptr<Member> m) : Owner(m, m.get()) {}
private:
Owner(unique_ptr<Member>& m, Member* ptr) : member(std::move(m)){
ptr->setOwnership(this);
}
protected:
const std::unique_ptr<const Member> member;
};