【问题标题】:access the unique pointer across the class without using reference or shared pointer在不使用引用或共享指针的情况下访问整个类的唯一指针
【发布时间】:2021-01-13 18:18:22
【问题描述】:

再次发帖, 存储在A类中的唯一指针,需要在B类中访问而不使用共享ptr或引用吗? (即)该指针的所有者应仅保留在 A 类中,并且不应共享指针的语义所有权。 func1, func2, func3 所有地方的唯一指针被多次访问。 代码片段有帮助,我是智能指针的新手。

class A
{
public:
    static A* Get();
    A();
    virtual ~A();
    std::unique_ptr<ABC> *Getter();
private:
    std::unique_ptr<ABC> uniquePointer;
}   

A.cpp

A::A() 
{
   uniquePointer = std::unique_ptr<ABC> new ABC();
}

A::Getter()
{
   return &uniquePointer; => This worked but it is not desirable.
}

b.h

#include <a.h>
class B {
private:
    func1();
    func2();
    func3();
}

B.cpp

B::func1()
{
    std::unique_ptr<ABC> *getPtrfunc1 = A::Get()->Getter();
}
B::func2()
{
    std::unique_ptr<ABC> *getPtrfunc2 = A::Get()->Getter();
}
B::func3()
{
    std::unique_ptr<ABC> *getPtrfunc3 = A::Get()->Getter();
}

【问题讨论】:

  • 您可以通过.get() 函数从unique_ptr 获取底层指针。所以你可以传递一个非拥有的指针。此外,建议使用std::make_unique 创建unique_ptr。但是对于您想要实现的目标,这个问题并不十分清楚
  • 好的,谢谢。这将起作用,类似于@Remy Lebeau 的建议。

标签: c++ singleton c++17 smart-pointers unique-ptr


【解决方案1】:

指针的语义所有权不应共享

根本不要绕过对unique_ptr 的访问。传递一个指向unique_ptr 拥有的ABC 的原始指针,例如:

class A
{
public:
    static A* Get();
    A();
    ABC* Getter();
private:
    std::unique_ptr<ABC> uniquePointer;
};
A::A() 
{
   uniquePointer = std::make_unique<ABC>();
}

A* A::Get()
{
    static A a;
    return &a;
}

ABC* A::Getter()
{
   return uniquePointer.get();
}
#include <a.h>

class B {
private:
    void func1();
    void func2();
    void func3();
}
void B::func1()
{
    ABC *getPtrfunc1 = A::Get()->Getter();
}

void B::func2()
{
    ABC *getPtrfunc2 = A::Get()->Getter();
}

void B::func3()
{
    ABC *getPtrfunc3 = A::Get()->Getter();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多