智能指针是否打破了头文件中最小化#include的原则?
Do smart pointers break the principle of minimizing #includes in header files?
我更喜欢在头文件中尽量减少#include
的使用,尽可能使用前向声明,我相信这是一种很好的做法。
bool IsFlagSet(MyObject *pObj);
但是,如果我在MyObject.h
中有typedef Ptr<MyObject> MyObjectPtr
并且API更改为:
bool IsFlagSet(MyObjectPtr pObj);
我现在不有 #include "MyObject.h"
吗?是否有其他方法可以解决这个问题,或者这只是使用智能指针的代价?
不,你不需要。你可以为一个不完整的类定义一个类型别名,模板参数可以是不完整的类型(参见c++ 11标准第14.3.1/2段):
#include <memory>
struct C;
typedef std::shared_ptr<C> ptrC; // C is incomplete here
struct C { void foo() { } };
int main()
{
ptrC p = std::make_shared<C>();
p->foo();
}
正如Pubby在注释中正确提到的,函数声明也不要求其签名中提到的类型是完整的:
struct C;
void foo(C); // C is incomplete here
struct C { };
#include <iostream>
void foo(C)
{
std::cout << "foo(C)" << std::endl;
}
int main()
{
C c;
foo(c);
}
不,std::shared_ptr<T>
被明确设计为只在T
前向声明时工作。当然,这并不适用于所有情况,但原理与普通指针相同。如果T
是前向声明的,你可以用std::shared_ptr<T>
做T*
能做的任何事情。
可以对不完整类型使用typedef。
但是使用智能指针类型的全名不是更好吗?
MyClassPtr
当然更短,但std::unique_ptr<MyClass>
实际上告诉我们如何使用这个指针。对于不太长的名称,我建议使用智能指针的全名
相关文章:
- 找到两对数字,使它们的乘积的绝对差最小化
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 超轻 - 如何最小化窗口
- 在C++中使用 GSL 最小化
- 在C++中最小化变量的范围
- 当只有一个线程主要使用该对象而其他线程很少使用它时,如何最小化该对象的互斥锁锁定?
- "最小化"按钮不会出现在 MFC 对话框中
- 从小于或等于某个 N 的数字列表中最小化或找到 n 个理想的子集和
- 如何排列二进制字符串以最小化它们之间的距离
- 最小化 C++ 中的内存使用
- 禁用 GPO 的空气抖动最小化
- 如何隐藏最大化和最小化按钮并在qml应用程序窗口中显示关闭按钮?
- 如何使用 stl 最小化 c++ 中所有打开的窗口
- 如何最小化嵌入式平台上的内存分配
- 可见程序或最小化程序时的过程ID更改
- 删除/最小化GIT合并冲突
- 当模式窗口最小化时,最小化所有应用程序窗口(在 Linux 上)
- 应用程序最小化时单击显示桌面/最小化全部
- 如何在Qt中打开外部应用程序并将其最小化到系统托盘
- 智能指针是否打破了头文件中最小化#include的原则?