Domanda

I am having difficulty with a crash using an auto_ptr. I am aware that you cannot store auto_ptr's in STL containers. But what about storing pointer values held by the auto_ptr inside a vector? If the auto_ptr's delete the stored object they point to, a subsequent destruction of a vector that stored these internal pointers causes my program to crash in the vectors Tidy_ method.

ClassA {
public:
   ClassA() {
      auto_pointer_1_.reset(new ClassP());
      auto_pointer_2_.reset(new ClassP());
      auto_pointer_3_.reset(new ClassP());
   };

   std::auto_ptr<ClassP> auto_pointer_1_;
   std::auto_ptr<ClassP> auto_pointer_2_;
   std::auto_ptr<ClassP> auto_pointer_3_;

};

ClassB {  
public: 
   ClassB(ClassA& a_class_a_) {
      vector_of_pointers_.push_back(a_class_a_.auto_pointer_1_.get());
      vector_of_pointers_.push_back(a_class_a_.auto_pointer_2_.get());
      vector_of_pointers_.push_back(a_class_a_.auto_pointer_3_.get());
   };

   std::vector<ClassP*> vector_of_pointers_;
};

void main(void) {

   ClassA* class_a_variable_ = new ClassA();

   ClassB* class_b_variable_ = new ClassB(*class_a_variable_);

   delete class_a_variable_;
   delete class_b_variable_;  <--- CRASH in std::vector Tidy_ method
}

Can anyone explain to me why the crash occurs? When the auto_ptr deletes its stored pointer, the associated pointer in the vector is no longer pointing to anything but why would that prevent the vector from properly destructing?

Thanks

È stato utile?

Soluzione

As shown there is no problem with the program when a stub ClassP is added that does nothing (and class is added where required, and main() changed to return int). The behavior you observe may be due to a corruption of the memory.

If any or all of ClassA, ClassB or ClassP actually have non-trivial destructors, it is possible that at least one of their destructor implementations has a bug that is causing undefined behavior. You should focus your attention on that.

Realize that std::auto_ptr has been deprecated, and you should use std::unique_ptr instead, as noted by Ben Voigt.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top