Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1088
  • Last Modified:

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

  • 2
1 Solution
>>>> 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:
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.
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.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now