gpt4 book ai didi

c++ - 工厂模式 : typedef Class *(createClassFunction)(void)

转载 作者:行者123 更新时间:2023-11-28 06:43:40 25 4
gpt4 key购买 nike

typedef Class *(createClassFunction)(void)(或另一种变体是 typedef Class* (__stdcall *CreateClassFunction)(void))代表什么?这是什么意思?我该怎么解释呢?特别是在工厂模式的背景下......

最佳答案

Reading C type expressions

createClassFunction 是一个不带参数并返回 Class * 的函数的 typedef。

通过该声明,指向此类函数的指针显然可以充当 Class工厂。用法可能如下:

// the class factory
Class * MostTrivialFactoryKnownToMan()
{
return new Class;
}

// another class factory
Class * CreateClassWithLog()
{
ClassWithLog * p = new ClassWithLog; // derived from Class
p->SetLogFile("log.txt");
return p;
}

// code consuming the class factory
void PopulateStars(createClassFunction * factory)
{
// creates many instances of `Class` through `factory`
Sky * sky = GetSky();
for(int i=0; i<sky->GetStarCount(); ++i)
{
Class * inhabitant = (*factory)();
sky->GetStar(i)->SetInhabitant(inhabitant);
}
}

// code deciding which factory to use
const bool todayWeWriteALog = (rand() %2) != 0;
createClassFunction * todaysFactory = todayWeWriteALog ?
&MostTrivialFactoryKnownToMan :
&CreateClassWithLog);

PopulateStars(factory);

__stdcall 是调用约定中编译器特定的属性更改(参数和返回值如何在调用者和实现之间传递)。这对于二进制兼容性通常很重要 - 例如当 Pascal 程序需要调用用 C 或 C++ 实现的函数时。

问题:

工厂函数返回原始指针。工厂和消费者之间必须有一个关于如何释放该指针的隐含契约(例如,通过 delete in 或 example)。为返回类型使用智能指针(例如 shared_ptr)将允许工厂确定删除策略。

工厂作为函数指针,可能不保存状态(比如日志文件名,需要硬编码在函数中,或者全局可用)。相反,使用可调用对象将允许实现可配置工厂。

关于c++ - 工厂模式 : typedef Class *(createClassFunction)(void),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25444313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com