首页 > 解决方案 > 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

任何要阅读的提示或资料我都会很感激!

标签: c++

解决方案


一般来说,我也认为这可能是一个 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();
}

推荐阅读