2011-03-23 4 views
0
void ClassA::Func() 
{ 
    static map<int, string> mapIntStr; 

    mapIntStr[0] = m_memberVariable0; <= just want to do once & m_memberVariable* are not static 
    mapIntStr[1] = m_memberVariable1; <= just want to do once 
    ... 
} 

변수 mapIntStr을 한 번만 초기화하고 싶습니다. 알다시피 초기화 함수를 정적 함수에 넣고 정적 함수를 호출하고 반환 값을 mapIntStr에 저장할 수 있습니다.C++ - 멤버 함수 내에서 정적 변수를 초기화하는 방법?

빠른 & 더러운 솔루션을 얻고 싶습니다. 내가 기억 하듯이, 정적 범위라고하는 것이 있습니다. 정적 함수를 호출하지 않고 mapIntStr을 초기화하고 싶습니다. 내가 어떻게 해?

당신에게 어떻게 그것에 대해

+2

정적 멤버 변수가 아닌 특별한 이유가 있습니까? – littleadv

답변

6
void ClassA::Func() 
{ 
    static map<int, string> mapIntStr; 

    if(mapIntStr.empty()){ 
     mapIntStr[0] = m_memberVariable0; 
     mapIntStr[1] = m_memberVariable1; 
     // ... 
    } 
} 

감사? :)
편집
글쎄, 가장 좋은 해결책은 을 기능 밖에서 클래스로 가져 오는 것입니다. 그리고 정적 함수 호출을 사용하지 않아도됩니다.

//in ClassA.h 
class ClassA{ 
public: 
    void Func(); 

    static map<int,string> InitStatic(); 
    static map<int,string> mapIntStr; 
}; 

//in ClassA.cpp 
#include "ClassA.h" 
void ClassA::Func(){ 
    // use mapIntStr 
} 

map<int,string> ClassA::InitStatic(){ 
    map<int,string> ret; 
    // init ret 
    return ret; 
} 

map<int,string> ClassA::mapIntStr = ClassA::InitStatic(); 

나는 알고있는 유일한 옵션에 관한 것입니다. 그래서 선택의 여지가 있습니다. 한 번 func에서지도를 초기화하거나 심지어 처음으로 ClassA 객체 (더 나은 버전)가 생성되고 empty()에 거의 아무런 전화도 걸지 않고 오버 헤드가 발생하여 생깁니다. 적절한 인라이닝 및 오버 헤드를 전혀주지 않거나 정적 초기화 기능을 사용합니다.

+0

이것은 최상의 솔루션이 아닙니다. b/c CPU가 if 조건을 확인하는 데 시간을 낭비 할 것입니다. 감사합니다. – q0987

+0

물론 가장 좋은 솔루션은 다른 것입니다. brb, 편집 중입니다. – Xeo

+0

@ q0987 업데이트. – Xeo

1

내부 구조체를 만들고 해당 구조체의 생성자에서 모든 것을 초기화 한 다음 해당 구조체의 정적 변수를 선언하십시오. 귀하의 경우를 들어

void fun() 
{ 
    struct setter 
    { 
     setter(){} 
    }; 

    static setter setup; 
} 

:

void ClassA::Func() 
{ 
    struct Map : public std::map<int, string> 
    { 
      Map() 
      { 
       (*this)[0] = something; 
       (*this)[1] = somethingElse; 
      } 
    } 
    static Map map; 
} 
0

는 여기에 내가 이런 경우에 사용하는 방법입니다.

#include <functional> 

class block 
{ 
public: 
    block(std::function<void()> func) 
    { 
    func(); 
    } 
}; 

이 정말 원시적 인 경량 클래스이지만,이 같은 것을 할하자 : 당신은 다음과 같은 클래스로 시작

void ClassA::Func() 
{ 
    static map<int, string> mapIntStr; 

    static block init_mapIntStr 
    { 
    []() 
    { 
     // Everything inside this block is called only once. 
     mapIntStr[0] = m_memberVariable0; 
     mapIntStr[1] = m_memberVariable1; 
    } 
    } 

    ... 

이 아마 모든 사람에게 아주 예쁜되지 않습니다,하지만 공장. 또한이 블록 클래스는 재사용이 가능합니다.

관련 문제