unique_ptr在指向的对象上调用operator[]()时出现分割错误

unique_ptr Segmentation fault when calling operator[]() on pointed to object

本文关键字:错误 分割 operator 调用 ptr 对象 unique      更新时间:2023-10-16

我正在努力把我的头围绕一个讨厌的运行时错误。这是一个有点代码发布,但我希望它不是太多的阅读和太少的诊断问题。由于某种原因,当我遵从它并使用操作符函数调用时,unique_ptr会爆炸。

class Dataset
{
  private:
    std::unique_ptr<File> file;
    std::unique_ptr<File> & getFile() throw () { return file; }
    std::unique_ptr<Properties> properties;
    std::unique_ptr<Properties> & getProperties() throw () 
    { 
      return properties; 
    }
  ...
}
class Properties
{
  private:
    std::map<const std::string, Property> container;
  public:
    Property & operator[](const std::string & s) {
      try
      {
        return container.at(s);
      }
      catch (std::out_of_range & e)
      {
        std::stringstream ss;
        ss << "Key "" << s << "" does not exist in collection in 
          file " << __FILE__ << " at line " << __LINE__;
        throw Exception::KeyNotFound(ss.str(), __FILE__, __LINE__);
      }
    }
  ...
}
class FrameCollection
{
  private:
    Dataset & dataset;
  public:
    FrameCollection();
  ...
}
FrameCollection::FrameCollection()
{
  Property property (
    dataset.getProperties()->operator[](PROPERTY_MAX_FRAMES)
  );
...
}

唯一指针在FrameCollection()中爆炸:

线程[1]14303 [core: 10] (suspend: Signal: SIGSEGV:Segmentation fault)std::_Rb_tree, std::_Select1st>, std::less, std::allocator>>::_M_begin() at stl_tree.h:502 0x7ffff7ba9d72
std::_Rb_tree, std::_Select1st>, std::less, std::allocator>>::lower_bound() at stl_tree.h:879 0x7ffff7bbbd4e
Std::map, Std::allocator>>::lower_bound() at stl_map.h:864 0x7ffff7bbba39
Std::map, Std::allocator>>::at() at stl_map.h:503 0x7ffff7bbb762bmd2::PropertyCollection::operator at persistenobject .cpp:140 0x7ffff7bb9137
bmd2::FrameCollection::FrameCollection() at FrameCollection.cpp:16 0x7ffff7bb5425
bmd2::Dataset::Dataset() at Dataset.cpp:68 0x7ffff7ba61f9
__gnu_cxx::new_allocator::construct>() at new_allocator.h:120 0x7ffff7ba3b67
std::allocator_traits>::_S_construct>() at alloc_traits.h:254 0x7ffff7ba3977
Std::allocator_traits>::construct>() at alloc_traits.h:393 0x7ffff7ba37b7
& lt;…多帧…>

问题是在你的FrameCollection类。你定义了一个引用,但没有在构造函数中初始化它。

class FrameCollection
{
private:
    Dataset & dataset;
public:
    FrameCollection();
    // ...
}
FrameCollection::FrameCollection()
{
   Property property (
      dataset.getProperties()->operator[](PROPERTY_MAX_FRAMES)
   );
   //...
}

当类中有引用变量时,构造函数应该接受引用并在初始化列表中初始化该成员:

class FrameCollection
{
private:
    Dataset & dataset;
public:
    FrameCollection( Dataset& );
    // ...
}
FrameCollection::FrameCollection( Dataset& d ) :
    dataset( d )
{
   Property property (
      dataset.getProperties()->operator[](PROPERTY_MAX_FRAMES)
   );
   //...
}