static std::string initialization

In C++ how do you do static std::string initialization in a class.
When I do it it leaks memory?
// test_static.cpp : Defines the entry point for the console application.
#include <stdlib.h>
#include <crtdbg.h>
#include "stdafx.h"
#include ".\test.h"
using namespace static_test;
int _tmain(int argc, _TCHAR* argv[])
  test my_test_class;
  _CrtMemState s1;
  _CrtMemCheckpoint( &s1 );
  _CrtMemDumpStatistics( &s1 );
	return 0;
#pragma once
#include <string>
namespace static_test
  class test
    static std::string string_20;
    // ctors and dtor
    test() {};
    virtual ~test() {};
    void doit();
} // end namespace
#include "StdAfx.h"
#include ".\test.h"
namespace static_test
  std::string test::string_20 = "12345678901234567890";
  void test::doit()
    std::string new_string = test::string_20;
} // end namespace

Open in new window

Who is Participating?
haggersrConnect With a Mentor Author Commented:
Please provide an example. I am confused because a std::string's memory is self-destructed, correct?
So do the strings destruct after the leak detector and before main exits? Please clue me in about std::string initialization and destruction.
>>>> When I do it it leaks memory?
Not really. The leak detector is only running before the static objects were deleted. If you will avoid that you need to change to a static pointer which was initialized with new operator. Then you could provide a static class member function which deletes the pointer and sets it to NULL. You would call that function before exiting your program.
haggersrAuthor Commented:
The real answer is that std::strings are iniyialized befoe main is called and destroyed after main exits. Therefore, the crtdbg leak check function will report the std::string as a leak. To correct for thid, instead of calling the leak check function before main exits, you can set an option too do leak checking when main is eneterd and it will only report true leaks from the applications normal block leakage.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.