修改unique_ptr的目标,并用它初始化const unique_ptr

时间:2015-11-06 15:32:26

标签: c++ c++11 unique-ptr

假设class OwnerMember 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

1 个答案:

答案 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;
};