假定class Owner
具有Member member
,该const
还必须具有指向其const
所有者的member
指针。将该指针提供给Owner
的构造函数中的member
,该构造函数接受指向组成Owner
的指针作为参数。
考虑unique_ptr
的构造函数:
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;
};
现在我要
member
为我处理Owner
的所有权,所以我尝试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;
};
尝试使用
const
的构造函数都不会编译。我该怎么做呢?原则上似乎没有理由为什么我不能这样做。我是否只是为了使用
unique_ptr
的方便而牺牲了之一? 最佳答案
将构造函数委派给救援人员:
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;
};