c++ - C++:类的静态实例
问题描述
我正在尝试创建此类的对象,但存储持续时间应该是静态的:程序必须从索引参数值 0 开始,一个接一个地在任何地方准确创建 storage_count (不是更多,不是更少)类型的对象到并包括 storage_count - 1。
class anywhere
{
public:
anywhere( std::string storage_duration_name, unsigned short index )
: storage_duration_name_( std::move( storage_duration_name )), index_( index )
{
std::cout << "constructor " << storage_duration_name_ << ' ' << index_ << std::endl;
}
~anywhere( )
{ std::cout << "destructor " << storage_duration_name_ << ' ' << index_ << std::endl; }
private:
const std::string storage_duration_name_;
const unsigned short index_;
anywhere( const anywhere & ) = delete;
anywhere( anywhere && ) = delete;
};
这里的问题是对象的数量是在运行时确定的,并且可能会在 0 <= count <=100 之间变化。由于不可能在循环内创建类的静态对象(它不会每次都创建它们,仅在第一次迭代时创建)或递归(这会产生未定义的行为)。我尝试过这样的事情,但我认为这样做可能很短。
//form main() ...
unsigned short storage_count = argv[ 2 ];//with checks focourse
unsigned short number = 0;
object_creator<anywhere>( storage_duration_name, number, storage_count );
//end of main() ...
template<class T>
void object_creator( std::string &storage, unsigned short current, unsigned short &num )
{
if ( storage == "static" )
{
if ( current > num )
{
return;
} else if ( current == 1 )
{
static T o1 = T( storage, 0 );
object_creator<anywhere>( storage, ++current, num );
} else if ( current == 2 )
{
static T o2 = T( storage, 1 );
object_creator<anywhere>( storage, ++current, num );
} else if ( current == 3 )
{
static T o3 = T( storage, 2 );
object_creator<anywhere>( storage, ++current, num );
} else if ( current == 4 )
{
static T o4 = T( storage, 3 );
object_creator<anywhere>( storage, ++current, num );
//..... for 100 of them
任何要阅读的提示或资料我都会很感激!
解决方案
一般来说,我也认为这可能是一个 XY 问题,但假设不是,唯一的方法似乎是使用递归在堆栈上创建对象。但是由于这些将在函数返回时被释放,因此您必须在递归函数内执行所有程序。这是通过将 a 传递std::function do_main
给递归对象创建者来完成的,这样当所有对象都还活着时,它就可以在最深的递归调用中调用它。一旦do_main
返回,堆栈上的所有对象都被释放。(为简单起见,我省略了对象名称等)。
template<class T>
void object_creator(int number_of_objects, std::function<void()>& do_main)
{
T object;
if(number_of_objects > 0) object_creator(number_of_objects - 1, do_main);
else do_main();
}
推荐阅读
- c# - 从进程外运行空间中获取 Powershell 对象
- google-maps - Google Maps 3.32 版中的新渲染器破坏了现有代码
- r - 拆分和重命名R中数据框中的重复列
- c# - 连接 ReadOnlySpan
- python - 将 jupyter 笔记本保存为 PDF 时,如何保留 pandas DataFrames 的样式背景颜色?
- github - 如何在 Bitbucket 和 github markdown 中显示数学表达式?
- java - 微服务中的观察者模式
- android - 存在绝对链接时,Jsoup connect 无法正常工作?
- javascript - 从 data.task 迁移到处理拒绝的民间故事
- web - 如何在 Adsense 中实施非个性化广告?