C++ std::shared_ptr, operator= 是否重载以使用复制构造函数?

C++ std::shared_ptr, is operator= overloaded to use copy constructor?

如果我执行以下操作:

class Foo
{
    std::shared_ptr<Bar> bar;
    Foo(std::shared_ptr<Bar> bar)
    {
        this->bar = bar;
    }
}
std::shared_ptr<Foo> func()
{
    std::shared_ptr<Bar> bar_ptr(new Bar());
    std::shared_ptr<Foo> foo_ptr(new Foo(bar_ptr));
    return foo_ptr;
}

foo_ptr in func() 的成员变量bar 中是否有一个有效的指针?似乎只有在设置 this->bar = bar 时才会复制构造函数参数。 std::shared_ptr 的 = 运算符是否被覆盖以始终调用复制构造函数?

复制构造函数和赋值运算符都会使接收方与您传入的接收方共享所有权。但是它们在内部执行是一个实现细节。

当然,如果 this->bar 正在管理某些东西,那么它会释放它的共享所有权(如果它是最后一个拥有它的人,那么 Bar 那里的任何东西都会被删除) .

But my concern here is that both this-> bar and bar in the constructor of Foo are the same reference meaning that there is really only one shared_ptr object in memory, but I have 2 variables referencing that shared_ptr.

它们不是引用,barthis->bar 是两个不同的 std::shared_ptr 对象,它们在赋值后将(在内部)指向内存中的同一位置(但它们仍然是两个不同的对象)。但是,std::shared_ptr 是一个 class,它知道有多少其他 std::shared_ptr 指向它(共享所有权),并且只会正确删除该对象一旦所有其他人都消失了(所以只有最后一个 std::shared_ptr 会摧毁它)。

此处 this->bar 强烈引用 bar 管理的内容:

Foo(std::shared_ptr<Bar> bar)
    {
        this->bar = bar;
    }

这里没有复制,您只是通过将 bar 分配给成员来增加 shared_ptr 的引用计数。

是的,您作为成员拥有的指针是有效的,因为生命周期由 shared_ptr 管理。