称为error的单例析构函数

Singleton destructor called error

本文关键字:析构函数 单例 error 称为      更新时间:2023-10-16
#pragma once
#include <time.h>        
class CTimer
{
    time_t _last;
    CTimer() { _last = time( NULL ); }
    CTimer(const CTimer &);
    CTimer& operator=(const CTimer&);
    ~CTimer();
public:
    static CTimer& getInstance(){        
        static CTimer instance;
        return instance;
    }
    float getDelta(){
        time_t now = time( NULL );
        float delta = (float)(now - _last);     
        return delta;
    }
    //should be called at the beginning of rendering function
    void update(){
        _last = time( NULL );
    }
};

这是我的定时器单例代码。我想这样使用它:在玩家类的某处:

posX += vel * CTimer::getInstance().getDelta();

在主循环文件中:

void gameLoop(){
CTimer::getInstance().update();
...
}

但是我得到这个错误:

1>主要。obj:错误LNK2019:未解析的外部符号"private: __thiscall CTimer::~CTimer(void)"(??1CTimer@@AAE@XZ)引用函数"void _cdecl public: static class getInstance & __cdecl CTimer::getInstance(void)':: 2':: ' dynamic atexit析构函数for 'instance " (void)"(? ? _Finstance@ ? 1 ? ? getInstance@CTimer@@SAAAV1@XZ@YAXXZ)

我认为这是因为主代码试图调用析构函数,循环结束后,我应该改为指针单例,但也许不是。你能告诉我怎么修吗?

main退出时,您的单例将被销毁(当然,如果它已初始化)。它的析构函数被调用。你必须实现它(至少是空的)。否则你的程序不能被链接

如果CTimer类的唯一成员是time_t变量,那么您不需要(未实现,因此链接错误)析构函数,复制构造函数和赋值操作符。只需注释这三行:这些函数将由编译器生成!

你在没有为析构函数写主体的情况下阻止了对象的析构,所以它会导致链接错误。请写析构函数体

~CTimer()
    {} //code to free any resource

示例代码:http://ideone.com/TqtLVX view_edit_box

您必须为析构函数提供实现,因为它在main返回时被调用:

~CTimer() {}

第一个问题:您是否希望唯一的实例被销毁?如果你想销毁它,你必须提供一个主体的析构函数(即使它是空的),或者必须不要自己声明(这会让它公开),但是应该不成问题)。在c++ 11中,您还可以将其声明为= default,它告诉编译器生成它想要生成的内容通常为实现生成。

然而,大多数情况下,您不希望单例对象是损害。使用单例的一个主要原因是解决初始化顺序问题;破坏它会留下这扇门打开了毁灭秩序的问题。常用的习语会不会使用静态指针指向单例,测试在实例函数中是否为空,以及分配如果是,则为新实例。(如果我能相信这个评论的话建议该类仅在呈现期间使用可能不重要,因为你不会和调用exit或从main)。