【发布时间】:2020-05-10 14:54:39
【问题描述】:
现在,我想,我必须在我的计划中做出一个重要的决定。任务如下:
我有一个class base,它将被多个派生类继承。派生类必须对base 成员的相同实例具有共享访问权限。另外,我想从外部访问那些“共享”Bases 成员:从包含所有派生类的第三个class Foo。根据我目前的经验,我想出了两个解决方案:
- 第一个是使用共享指针。使用
structs、ints 并将所有内容放在构造函数中以简化操作。
struct Base
{
std::shared_ptr<int> m_1 = nullptr;
std::shared_ptr<int> m_2 = nullptr;
};
struct Derived_1 : Base
{
// using Base members and doing other stuff
};
struct Derived_2 : Base
{
// using Base members and doing other stuff
};
struct Foo
{
std::shared_ptr<int> m_1 = std::make_shared<int>();
std::shared_ptr<int> m_2 = std::make_shared<int>();
Derived_1 _d1;
Derived_2 _d2;
Foo()
{
_d1.m_1 = this->m_1;
_d1.m_2 = this->m_2;
_d2.m_1 = this->m_1;
_d2.m_2 = this->m_2;
}
};
我可以从Foo 和派生类访问相同的m_1 和m_2。
- 第二种解决方案涉及使用
static关键字:
struct Base
{
static std::shared_ptr<int> m_1;
static std::shared_ptr<int> m_2;
};
// providing definitions for Base::m_1 and Base::m_2 ...
// Derived classes stay the same as in first example.
class Foo
{
std::shared_ptr<int> m_1;
std::shared_ptr<int> m_2;
Foo()
{
this->m_1 = Base::m_1;
this->m_2 = Base::m_2;
}
};
在这两种情况下,我都取得了相同的结果(真的吗?)。一种方法比另一种方法有什么优势吗?他们有什么隐藏的缺点?什么是更常见的方法,为什么?我对其他方法很好奇。我在VS17下使用的是c++17。
【问题讨论】:
-
在这两种情况下都打印
sizeof(Base),这可能很有启发性。使用第一种方法,您会在Base的每个实例中存储相同数据的副本,从而浪费空间。 -
不清楚为什么你甚至有
Base类,它似乎没有任何用处。你可能想要一个单例来存放共享数据。 -
Base 本身并不多,它只拥有那些共享成员,但共享成员是那些完成所有工作的人。派生类必须能够访问来自 Base 成员的某些计算结果。我同意单例也可以是一个解决方案。
-
你真正想要实现什么?如果所有
Foos 都需要访问公共int,则使其成为Foo的静态成员。我已经写了一个答案,但我仍然不明白这一切有什么好处。也许xy problem -
顺便说一句,您的标题要求
static Tvsshared_ptr<T>,但您的代码是static shared_ptr<T>vsshared_ptr<T>
标签: c++ inheritance static shared-ptr