Inheritance from CString caused a memory exception

I have the following string class inheriting from MFC CString

class TString : public CString
{
public:
    TString() : CString(_T(""))
    {
    }

    TString(LPCTSTR str) : CString(str)
    {
    }
};

I had a memory exception in a method that often used the + operator with TString, so I tried to do a test like this

TString str;
TCHAR buffer[] = "Hello world, Hello world, Hello world, Hello world, Hello world, Hello world";

uint i = 0;
while(i++ < 100000000)
{
    str = buffer;
    str += buffer;
}

which took up a lot of memory and ended with an exception from memory, this is a shot to change memory from the task manager after the last code was executed

enter image description here

when I replaced TString with CString, it was normal, it took time and memory deletion and the memory was stable in the task manager, as in this picture

enter image description here

I tried the following 2 states

  • I created another exe application that depends on the same Library that contains the TString class, which worked very well, like CString
  • Sleep (1) while, , ​​?

EDIT:

, . CString , std::string. , , malloc , , , CWinAppEx, , InitInstance. 4

int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;//<====this is the evil after comment everything is fine
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);

, . .

tmpDbgFlag | = _CRTDBG_DELAY_FREE_MEM_DF;

. , , , .

+3
2

, , . " ++: 55 , " .

, getTimeKeeper (, AtomicClock), (.. TimeKeeper *) (TimeKeeper) . , ++ , , undefined. , . to getTimeKeeper , AtomicClock , AtomicClock (.. AtomicClock), , , AtomicClock . (.. TimeKeeper), , , " " . , .

, , , , . , -, , , .

, , . , , . - , , , , , .

.

class TString /* do not derive from CString */
{
private:
  CString m_string;
    TString() :
      m_string()
  {
  }

  TString(const TCHAR *str) :
    m_string(str)
  {
  }

  int GetLength() const
  {
    return m_string.GetLength();
  }

  /* All the other functions in the CString class here. */

  /* Your additions to the CString class here. */
}

, MFC CString , , , , .

template< typename BaseType >
class TStringT
{
    /* The same as above but use BaseType instead of TCHAR. */
}

.

typedef TStringT< wchar_t > TStringW;
typedef TStringT< char > TStringA;
typedef TStringT< TCHAR > TString;

, .

+2

, .

TString :

TString& operator=(LPCTSTR src)
{
    CString::operator=(src);

    return( *this );
}

TString LPTSTR, str = buffer;. TString LPTSTR TString . , .

0

All Articles