同一个 shared_ptr 用于多个对象?

huangapple go评论63阅读模式
英文:

Same shared_ptr for multiple objects?

问题

以下是代码的中文翻译部分:

#include <memory>
#include <iostream>

class C {};

class A {
public:
    A(std::shared_ptr<C> c) : c_(std::move(c)) {}
private:
    std::shared_ptr<C> c_;
};

class B {
public:
    B(std::shared_ptr<C> c) : c_(std::move(c)) {}
private:
    std::shared_ptr<C> c_;
};

int main()
{
    std::shared_ptr<C> c = std::make_shared<C>();
    A a(std::move(c));
    B b(std::move(c)); // 这会导致运行时错误,因为 c 在移动到 a 后变为 null。
    return 0;
}
英文:

Question

I have 3 classes, A, B, C as following. What is the best way to handle the runtime error? what options we have here? or we have to create one C shared_ptr for A/B each;

#include &lt;memory&gt;
#include &lt;iostream&gt;

class C {};

class A {
public:
    A(std::shared_ptr&lt;C&gt; c) : c_(std::move(c)) {}
private:
    std::shared_ptr&lt;C&gt; c_;
};

class B {
public:
    B(std::shared_ptr&lt;C&gt; c) : c_(std::move(c)) {}
private:
    std::shared_ptr&lt;C&gt; c_;
};

int main()
{
    std::shared_ptr&lt;C&gt; c = std::make_shared&lt;C&gt;();
    A a(std::move(c));
    B b(std::move(c)); // This would cause a runtime error, since c is null after being moved to a.
    return 0;
}

答案1

得分: 1

std::shared_ptr的目的是共享所有权

如果这是你的意图,你只需将它复制并删除所有对std::move的使用。

这是因为std::shared_ptr正在使用复制构造函数(以及析构函数)来跟踪共享对象的使用计数(允许在使用计数降到0时释放它)。

修复版本:

#include <memory>
#include <iostream>

class C {};

class A {
public:
    A(std::shared_ptr<C> c) : c_(c) {}
private:
    std::shared_ptr<C> c_;
};

class B {
public:
    B(std::shared_ptr<C> c) : c_(c) {}
private:
    std::shared_ptr<C> c_;
};

int main()
{
    std::shared_ptr<C> c = std::make_shared<C>();
    A a(c);
    B b(c);
    return 0;
}

在线演示 - Godbolt

英文:

The purpose of std::shared_ptr is to share ownership.

If this is what you intend here, you simply need to copy it around and remove all your usages of std::move.

This is because std::shared_ptr is utilizing the copy-constructor (together with the destructor) to keep track of the use-count of the shared object (allowing to release it when it drops to 0).

A fixed version:

#include &lt;memory&gt;
#include &lt;iostream&gt;

class C {};

class A {
public:
    A(std::shared_ptr&lt;C&gt; c) : c_(c) {}
private:
    std::shared_ptr&lt;C&gt; c_;
};

class B {
public:
    B(std::shared_ptr&lt;C&gt; c) : c_(c) {}
private:
    std::shared_ptr&lt;C&gt; c_;
};

int main()
{
    std::shared_ptr&lt;C&gt; c = std::make_shared&lt;C&gt;();
    A a(c);
    B b(c);
    return 0;
}

Live demo - Godbolt

huangapple
  • 本文由 发表于 2023年5月13日 11:30:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76240946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定