英文:
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 <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)); // 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;
}
英文:
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 <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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论