2012-06-19 3 views
0

Привет У меня есть этот кодПочему мой триплетный объект уничтожается?

class Triplets 
{ 
public: 
int nVal1; 
int nVal2; 
NodeT *ptrNode; 
bool bUpdate; 

Triplets() 
{ 
    cout << "creating empty triplet" << endl; 
    nVal2 = 0; 
    nVal1 = 0; 
    bUpdate = false; 
    ptrNode = NULL; 
} 

~Triplets() 
{ 
    cout << "destroying triplet" << endl; 
    delete ptrNode; 
} 

Triplets(int nVal1, int nVal2, bool bUpdate, NodeT *ptrNode) 
{ 
    cout << "creating triple with values" << endl; 
    this->nVal2 = nVal2; 
    this->nVal1 = nVal1; 
    this->bUpdate = bUpdate; 
    this->ptrNode = ptrNode; 
} 
}; 

Это использование

void find_triplets(NodeT *ptrRoot) 
{ 


    if (ptrRoot != NULL) 
    { 
    find_triplets(ptrRoot->left); 
    find_triplets(ptrRoot->right); 


    cout << "find triplets and save them to the queue" << endl; 
     cout << " we hit a hot spot is null the root, nothing to see here move along boys" << endl; 

    if(ptrRoot->left != NULL && ptrRoot->right != NULL) 
     { 

     if (ptrRoot->left->done == true && ptrRoot->right->done == true) 
     { 
     cout << "we got one of 2 sons true so do something, this are the sons "<< ptrRoot->left->key_value << " " << ptrRoot->right->key_value << endl;   

     cout << "sum them and put it in the father and set it to true " << endl; 
     ptrRoot->key_value = ptrRoot->left->key_value + ptrRoot->right->key_value; 
     ptrRoot->done = true; 


     cout << "thread queue " << endl; 
     Triplets triplet(ptrRoot->left->key_value, ptrRoot->right->key_value, ptrRoot->done, ptrRoot); 
     qThreads.push(triplet); 
     } 
    } 
    } 
    } 

И это главное

MyThread mt; 
mt.start(); 
mt.run(); 
cout << "sum = " << mt.sum(&bt) << endl; 
THREADS_HOW_MANY = boost::thread::hardware_concurrency(); 
std::cout << THREADS_HOW_MANY << std::endl; 

while (!bt.Values_to_do.empty()) 
{ 
    cout << "da vals to sum are these " << bt.Values_to_do.front() << " and aready done " << bt.values_done.front() << endl; 
    bt.Values_to_do.pop(); 
    bt.values_done.pop(); 
} 

    while(!mt.qThreads.empty()) 
{ 
cout << "da triplet are " << mt.qThreads.front().nVal1 << " " <<mt.qThreads.front().nVal2 << " " 
     << mt.qThreads.front().ptrNode << " " << mt.qThreads.front().bUpdate 
     << endl; 
mt.qThreads.pop(); 

} 

Все это дает мне этот результат (очевидно, неправильно)

done lets chek 
    find triplets 
    find triplets and save them to the queue 
    we hit a hot spot is null the root, nothing to see here move along boys 
    find triplets and save them to the queue 
    we hit a hot spot is null the root, nothing to see here move along boys 
find triplets and save them to the queue 
we hit a hot spot is null the root, nothing to see here move along boys 
we got one of 2 sons true so do something, this are the sons 2 8 
sum them and put it in the father and set it to true 
thread queue 
creating triple with values 
destroying triplet 
find triplets and save them to the queue 
we hit a hot spot is null the root, nothing to see here move along boys 
find triplets and save them to the queue 
we hit a hot spot is null the root, nothing to see here move along boys 
find triplets and save them to the queue 
we hit a hot spot is null the root, nothing to see here move along boys 
we got one of 2 sons true so do something, this are the sons 11 15 
sum them and put it in the father and set it to true 
thread queue 
creating triple with values 
destroying triplet 
find triplets and save them to the queue 
we hit a hot spot is null the root, nothing to see here move along boys 
we got one of 2 sons true so do something, this are the sons 19976608 19976464 
sum them and put it in 
the father and set it to true 
thread queue 
creating triple with values 
destroying triplet 
the gran total is 19976320 

Теперь мой q - это то, почему мой триплетный объект не добавляется в очередь и сейчас уничтожается, вот почему сумма выходила наружу. Благодарю.

+0

Для меня, глядя на ваш код, неясно, чего вы хотите достичь, поэтому неясно, что следует изменить. Однако общее управление памятью, удаление узла, не вынимая его из дерева и действующее только тогда, когда и левое, и правое не является нулевым, похоже на проблемы. – stefaanv

+0

Я не делаю этого, что класс дерева позаботится об этом, должен долго размещать его здесь, этот класс - это триплеты, у которых есть 2 сына с числами и указатель на отца, чтобы сохранить сумму. Поэтому я хочу сохранить их в очереди, чтобы фактический объект мог модифицировать его по своему усмотрению. –

+0

Но узел удаляется в вашем деструкторе триплета, и вы создаете новый триплет с указателем на узел, затем выталкиваете копию в очередь и позволяете уничтожать новую Триплет при выходе из области, которая удаляет узел, не будучи взятым от дерева. – stefaanv

ответ

0

Tl; др - то, что всплывает, что у вас есть деструктор, который управляет памятью:

~Triplets() 
{ 
    cout << "destroying triplet" << endl; 
    delete ptrNode; 
} 

еще не конструктор копирования и операторы присваивания. Попробуйте реализовать их.

+0

да я позабочусь о указателе, зачем мне это нужно? –

+0

@ user1423656 подчиняться правилу трех. –

+0

@ user1423656 см. Http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) –

0

Вы, кажется, создавать копии Triplets класса:

Triplets triplet(ptrRoot->left->key_value, ptrRoot->right->key_value, ptrRoot->done, ptrRoot); 
qThreads.push(triplet); 

В зависимости от декларации qThreads, необходимо сначала создать экземпляр Triplets имени triplet, а затем, когда вы толкаете его в qThreads он копируется. Затем, когда область выходит (на следующем }), объект triplet уничтожен. Это, конечно, означает, что указатель внутри него и указатель, который теперь имеет копию, теперь будут недействительными.

+0

Да, я создаю или больше хочу создать несколько объектов и добавить их в очередь. qThreads - это очередь qThreads; мне не нужна копия, как я говорю, что я хочу, чтобы этот объект в очереди не был копией. –

+0

@ user1423656 Вы помещаете _copy_ в очередь, а _original_ уничтожается. Подумайте, что это будет делать, например, с вашим указателем. –

+0

поэтому, если я хочу объект, чтобы перейти в очередь, а не какую-то копию, создать новый триплет объекта и добавить его в очередь. –

Смежные вопросы