2014-08-27 6 views
0

저는 창에서 서로 다른 위치에 이미지 시퀀스를 그리는 프로그램 중 하나에 대한 클래스가 있습니다. 클래스는 여러 개의 인스턴스를 가지고 있지만 창 안의 모든 위치에서 그려지는 이미지 시퀀스가 ​​같습니다. 내가하는 나는 .cpp 파일에서여러 클래스에서 개인 정적 변수 사용

class Drawer{ 
private: 
static ImageSequence imgSequence; 
}; 

변수로 정적 이미지 시퀀스 변수가 메모리를 먹는 피하기 위해 여러 개의 이미지 시퀀스를 initializaing 클래스의 여러 인스턴스를 방지하고자, 나는 정적을 초기화하기 위해 다음을 수행하고 var. 각 서랍 클래스의 인스턴스가 다시 프레임 시간을 미리로드하지 않도록 이러한 방법을 넣을 수있는 위치에 대한 혼란 -

#include "Drawer.h" 

ImageSequence Drawer::imgSequence = ImageSequence(); 

는 그러나, 나는 이미지 시퀀스의 경로를 지정하고 알을 미리로드하는 두 가지 방법 프레임이 있습니다. C++에서는 어떻게 되었습니까?

--EDIT 다음과 같은 두 가지 방법이 필요합니다. i) loadSequence, ii) preloadAllFrames();

loadSequence(string prefix, string firstFrame, string lastFrame){ 
    for(int i=0;i<numFrames;++i){ 
    //adds and pushes values of all the files in the sequence to a vector 
    } 
} 

preloadAllFrames(){ 
for(int i=0;i<numFrames;++i){ 
//create pointers to image textures and store then in a vector so that it doesn't take time to load them for drawing 
} 
} 
+0

말 : – pts

+0

번역 단위 간의 순서가 정의되지 않았기 때문에 정적 초기화 (예 :'ImageSequence Drawer :: imgSequence = ImageSequence();)는 안전하지 않습니다. – pts

+0

@pts : 대부분의 경우 하나의'static' 객체를 사용하여 다른 '정적'객체를 초기화하는 경우에만 사용합니다. 대답이 아니라 '정적'변수 대신에 플라이급 패턴 (예 : 부스트로 구현)을 사용하지 않는 이유는 무엇입니까? –

답변

0


은 이미지와 동반 부울 값이 이미지가 이미로드 된 경우로드하려고 할 때 선택합니다. 프로그램이 매 프레임마다로드하는 대신 프로그램을 한 번만 초기화 할 때로드 할 수도 있습니다. * 나는 두 가지 방법을 가지고 * 당신은

class Drawer{ 
private: 
    static std::unique_ptr<ImageSequence> imgSequence; 
public: 
    static void initializeMethod1() 
    { 
     if(imgSequence) return; // or throw exception 
     imgSequence.reset(new ImageSequence(...)); 
     ... 
    } 

    static void initializeMethod2() {} 
    { 
     if(imgSequence) return; // or throw exception 
     imgSequence.reset(new ImageSequence(...)); 
     ... 
    } 

    static ImageSequence &getSequence() 
    { 
     if(!imgSequence) throw std::runtime_error("image sequence is not intialized"); 
     return *imgSequence; 
    } 
}; 
0

그냥 대신 인스턴스의 정적 포인터를 가지고 정적 방법으로 초기화합니다. 이 두 가지 방법 중 (단순화 된) 코드를 게시하여 원하는 것을 더 잘 이해할 수 있도록하십시오.
+1

이것은 스레드로부터 안전하지 않습니다. C++ 11에서는'getSequence'에서 함수 - 로컬'static' 변수가 작동합니다 (일부 C++ 98 컴파일러에서도 작동 할 수 있습니다). –

+0

@ BenjaminBannier OP에서 코드가 스레드로부터 안전해야한다고 묻는 곳을 놓친 것 같습니까? – Slava

+0

쉬운 경우 왜 안되나요? https://stackoverflow.com/questions/1661529/is-meyers-implementation-of-singleton-pattern-thread-safe? –