通常情况下
init
-like函数表示缺少适当的构造函数。给定的要求清楚地导致了两个具有专用构造函数的类:
class hwPeripherals
{
private: static ::std::atomic_bool s_construction_attempted;
// instead of init_some_hw_peripherals
public: hwPeripherals(void)
{
// Check that no attempts of hwPeripherals construction happened yet.
if(s_construction_attempted.exchange(true))
{
// Throw an exception.
}
// Initialization... Throw an exception if fails.
}
};
class myClass
{
private: myClass(void) = delete;
// instead of init
public: explicit myClass(hwPeripherals & peripherals)
{
// Initialization... Throw an exception if fails.
}
public: void perform(void);
};
这种调用perform用户的方法需要实例化
myClass
首先,为了做到这一点,用户需要实例化
hwPeripherals
:
hwPeripherals peripherals{};
myClass obj{peripherals};
obj.perform();