假定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;
};

10-08 12:41