2017-10-06 1 views
2

저는 나뭇 가지로 구성된 나무를 만들고 있습니다. 내 일을 위해서, 나는 가지를 추적해야하고, 그렇게하기 위해서, 나는 그것들을 벡터 목록에 저장하고 싶다. 아래 코드 스 니펫에 표시된 생성자와 함수 모두에서이 벡터 변수를 전역 변수로이 파일에 저장합니다.벡터 목록을 전역 변수로 저장할 수 있습니까?

여기 까다로운 부분은 내가 알 수있는 한 반복기가 제대로 작동하지 않는 것과 관련이 있다는 오류 메시지 (Visual Studio 2013에서 실행 중)가 표시된다는 것입니다. branchList.push_back (root) 및 branchList.resize()를 호출 할 때마다 오류 메시지가 나타납니다. branchList.size()는 오류를 발생시키지 않습니다.

내 질문은 : 내가 무엇을 놓치고 /이 작품을 만들기 위해 이해가 안되니? 내가 branchList 벡터를 배치했다면; 생성자의 처음에는 모든 것이 의도 한대로 작동합니다. 그러나 나중에 다른 함수에서도 사용해야하기 때문에 이것은 도움이되지 않습니다.

내가 사용중인 파일의 관련 코드 스 니펫.

skeletonBuilder.h :

class TreeSkeleton { 

public: 
    TreeSkeleton(); 
    void growTree(); 
}; 

skeletonBuilder.cpp :

#include "skeletonBuilder.h" 
#include <cstdint> 
#include <vector> 


typedef struct branch { 
    branch *parent; 
    vec3 position; 
    vec3 direction; 
} branch; 

//used by constructor + "treeGrow" function 
std::vector<branch> branchList = {}; 

TreeSkeleton::TreeSkeleton() { 
    //instantiate the tree root as a starting position. 
    branch root; 
    root.parent = NULL; 
    root.position = vec3(0, 0, 0); 
    root.direction = vec3(0, 1, 0); 

    branchList.size(); //works fine 
    branchList.resize(100); //Crashes here 
    branchList.push_back(root); //Crashes here 
} 

TreeSkeleton::growTree() { 
    //pushing more branches to branchList 
} 

MAIN.CPP :

#include "skeletonBuilder.h" 

TreeSkeleton tree; 

int main(int argc, char *argv[]) { 

    return 0; 
} 

내가 무엇입니까 오류 메시지 :

Unhandled exception at 0x00507077 in OpenGL_project_Debug.exe: 0xC0000005: Access violation reading location 0x40EAAAB4. 

오류 메시지는 "벡터"라는 파일에 다음 코드로 나를 취

#if _VECTOR_ORPHAN_RANGE 
void _Orphan_range(pointer _First, pointer _Last) const 
    { // orphan iterators within specified (inclusive) range 
    _Lockit _Lock(_LOCK_DEBUG); 
    const_iterator **_Pnext = (const_iterator **)this->_Getpfirst(); 
    if (_Pnext != 0) 
     while (*_Pnext != 0) //<----------------This is the row that it gets stuck on 
      if ((*_Pnext)->_Ptr < _First || _Last < (*_Pnext)->_Ptr) 
       _Pnext = (const_iterator **)(*_Pnext)->_Getpnext(); 
      else 
       { // orphan the iterator 
       (*_Pnext)->_Clrcont(); 
       *_Pnext = *(const_iterator **)(*_Pnext)->_Getpnext(); 
       } 
    } 
+0

당신이 완전히 전역을 제거하는 것이 더 나은 – UnholySheep

답변

1

전역 개체의 초기화 순서는 구현 파일 사이 보장 할 수 없습니다. main.cpp 또는 skeletonBuilder.cpp의 전역을 먼저 알 수있는 방법은 없습니다. 귀하의 경우 TreeSkeleton treestd::vector<branch> branchList 전에 초기화되므로 문제가 발생할 수 있습니다. TreeSkeleton의 생성자는 초기화되지 않은 동작 인 초기화되지 않은 branchList을 사용해야합니다. 해결책은 인 순서로 전역을 배치하는 것입니다.

하나의 해결책은 로컬 정적 변수 branchList을 만드는 것입니다. 이러한 변수는 처음 만났을 때 초기화되도록 보장됩니다. 예를 들어

:

class TreeSkeleton { 

public: 
    TreeSkeleton(); 
    void growTree(); 

private: 
    static std::vector<branch> & getBranches(); 
}; 

std::vector<branch> & TreeSkeleton::getBranches() 
{ 
    // branchList is initialized the first time this line is encountered 
    static std::vector<branch> branchList; 
    return branchList; 
} 

TreeSkeleton::TreeSkeleton() 
{ 
    //instantiate the tree root as a starting position. 
    branch root; 
    root.parent = NULL; 
    root.position = vec3(0, 0, 0); 
    root.direction = vec3(0, 1, 0); 

    auto & branchList = getBranches(); 
    branchList.size(); 
    branchList.push_back(root); // Should be fine now 
} 
+0

을 받고있는 * 정확한 * 오류 메시지를 붙여 복사하시기 바랍니다. 나는 이러한 변수가 전역 변수가 될 필요가 없다는 것을 알 수있다. 벡터가 트리 내에 포함되는 것 (모든 트리 사이에서 공유 될 경우 멤버 또는 정적으로 사용되는 경우)과 트리가 주 함수 내에서 선언되는 것보다 좋다. –

+0

좋아요, 당신이 말하는 것을 이해하고 작성한 기능을 사용하려고합니다. 그러나 struct 브랜치가 .cpp 파일에 구현되어 "정적 표준 : 벡터 ..."이 "브랜치"가 무엇인지 알지 못하는 것이 하나의 문제입니다. –

+0

필요한 경우 구현 파일에서 정적 멤버 함수를 자유 함수로 변경할 수 있습니다. –

관련 문제