【发布时间】:2017-08-03 14:31:17
【问题描述】:
我有一个代码,其中一些类通过设计使用工厂函数来生成实际类,而另一些则不使用。许多类都实现了同名的函数,并且这些函数被顺序调用(见下文)。这种设计导致混合了指向对象和对象本身的智能指针。下面的代码是不是设计不好,我应该到处使用智能指针吗?
#include <iostream>
#include <memory>
class A
{
public:
void print_name() { std::cout << "A\n"; }
};
class B
{
public:
virtual void print_name() = 0;
static std::unique_ptr<B> factory(const int n);
};
class B1 : public B
{
public:
void print_name() { std::cout << "B1\n"; }
};
class B2 : public B
{
public:
void print_name() { std::cout << "B2\n"; }
};
std::unique_ptr<B> B::factory(const int n)
{
if (n == 1)
return std::make_unique<B1>();
else if (n == 2)
return std::make_unique<B2>();
else
throw std::runtime_error("Illegal option");
}
int main()
{
A a;
std::unique_ptr<B> b1 = B::factory(1);
std::unique_ptr<B> b2 = B::factory(2);
// The block below disturbs me because of mixed . and ->
a.print_name();
b1->print_name();
b2->print_name();
return 0;
}
编辑
我在下面的 cmets 后面的示例中添加了智能指针。
【问题讨论】:
-
一致的代码更容易理解和维护。
-
所以您建议也将
a设为指针? -
正如 Valentin 下面提到的,原始指针在现代 C++ 代码中确实不受欢迎。在这种情况下,我会使用 std::unique_ptr 。您应该研究智能指针,以确保您了解哪个更适合您。
-
@Sergei,请阅读我对 Valentin 帖子的评论。这不是关于智能指针与普通指针的讨论。
标签: c++ class oop pointers reference