【问题标题】:Point raw pointer to a shared_ptr将原始指针指向 shared_ptr
【发布时间】:2021-11-15 11:47:07
【问题描述】:

我在休息 1 年后开始使用 C++ 编程,但我在这里和那里都遇到了困难(并不是说在休息之前我真的知道)。

我目前的问题是不知道如何正确使用指针。

我有以下std::vector

std::vector<std::shared_ptr<IHittable>> world;

其中IHittableHittable 对象的接口。

现在,在这个std::vector 中,推送了IHittable 的多个派生,例如SphereTriangle 等。

每个派生类都有一个函数intersects(),如下所示:

Intersection Sphere::intersects(const Ray & ray)
{
    auto x = ...
    ...
    return {x, this};
}

Intersection 看起来像这样:

class Intersection
{
    public:
        Intersection(double t, IHittable * object);
        [[nodiscard]] double t() const;
        [[nodiscard]] IHittable * object() const;
    private:
        double t_;
        IHittable * object_ = nullptr;
};

我真的不知道如何正确编写这段代码。

我需要从一个对象的成员函数intersects() 返回一个this 指针,该对象本身是动态分配的并存储在std::shared_ptr 中。

有没有办法解决这个问题?

另一个例子:

std::vector<std::shared_ptr<IHittable>> world;
world.push_back(std::make_shared<Sphere>());
auto s = Intersection(4.0, world[0]);

应该可以。

PS:没有std::shared_ptr,我可以创建多个std::vectors:

std::vector<Sphere> spheres;
std::vector<Triangles> spheres;
...

但是恕我直言,一次迭代每个对象会很好。

PS2:我现在正在使用 shared_from_this() 并且我的大部分代码都可以正常工作,谢谢。

【问题讨论】:

  • 也许您正在寻找std::enable_shared_from_this 及其shared_from_this() 方法?更改 Intersection 以保存 std::shared_ptr&lt;IHittable&gt; 而不是原始的 IHittable* 指针。
  • 如果你有共享指针,你也可以共享它们,否则你在共享上花费资源而不使用它并告诉读者变量是共享的,而实际上它不是。对人们撒谎,他们对如何最好地使用您的代码做出错误的判断。
  • 对不起,为什么this 不起作用?您是否担心保留IHittable 的生命周期?
  • @JeremyWest,用“this”我有这个错误“i.stack.imgur.com/H45ns.png”。
  • 哦,我明白了,所以你的意思是 auto s = Intersection(4.0, world[0]); 行失败,对吧?试试这个:auto s = Intersection(4.0, world[0].get());

标签: c++ oop inheritance polymorphism shared-ptr


【解决方案1】:

我认为这听起来很适合 std::enable_shared_from_this,正如 Remy 在 cmets 中指出的那样。

我制作了一个简化的示例,希望能够清楚地说明如何使用它来实现您所追求的目标。

class Intersection;

class IHittable : public std::enable_shared_from_this<IHittable> { 
public:
    virtual Intersection intersects( ) = 0;
    virtual void print( ) const = 0;
    virtual ~IHittable( ) = default;
};

class Intersection {
public:
    Intersection( std::shared_ptr<IHittable> object )
        : object_{ std::move( object ) }
    { }

    void print_shape( ) const {
        object_->print( );
    }
private:
    std::shared_ptr<IHittable> object_;
};

class Square : public IHittable {
public:
    Intersection intersects( ) override {
        return Intersection{ shared_from_this( ) };
    }

    void print( ) const override {
        std::cout << "Square\n";
    }
};

int main( ) {
    std::vector<std::shared_ptr<IHittable>> objects{ 
        std::make_shared<Square>( ) };

    const auto intersect{ objects.front( )->intersects( ) };
    intersect.print_shape( );
}

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2019-09-29
    相关资源
    最近更新 更多