C++ 在指向的对象上调用运算符[]()时出现唯一的_ptr分段错误
我正在努力解决一个严重的运行时错误。这是一个有点代码后,但我希望它不是太多的阅读和太少的诊断问题。由于某种原因,当我遵从它并使用操作符函数调用时,unique_ptr正在爆炸C++ 在指向的对象上调用运算符[]()时出现唯一的_ptr分段错误,c++,c++11,C++,C++11,我正在努力解决一个严重的运行时错误。这是一个有点代码后,但我希望它不是太多的阅读和太少的诊断问题。由于某种原因,当我遵从它并使用操作符函数调用时,unique_ptr正在爆炸 class Dataset { private: std::unique_ptr<File> file; std::unique_ptr<File> & getFile() throw () { return file; } std::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)
);
...
}
类数据集
{
私人:
std::唯一的_ptr文件;
std::unique_ptr&getFile()throw(){return file;}
std::独特的ptr属性;
std::unique_ptr&getProperties()抛出()
{
归还财产;
}
...
}
类属性
{
私人:
映射容器;
公众:
属性和运算符[](const std::string&s){
尝试
{
返回集装箱。在(s);
}
捕获(标准:超出范围和e)
{
std::stringstream-ss;
ss::_M_begin()在stl_树上。h:502 0x7ffff7ba9d72
std::_Rb_tree,std:_Select1st>,std::less,std::allocator>>::stl_tree的下界()。h:879 0x7FF7BBD4e
std::map,std::allocator>>::stl_map的下界()。h:864 0x7FF7BBA39
std::map,std::allocator>>:at()位于stl_map.h:503 0x7FFFF7BB762
bmd2::PropertyCollection::PersistentObject.cpp处的运算符:140 0x7ffff7bb9137
FrameCollection.cpp处的bmd2::FrameCollection::FrameCollection():16 0x7ff7bb5425
数据集处的bmd2::Dataset::Dataset().cpp:68 0x7FF7BA61F9
__gnu_cxx::新建_分配器::在新建_分配器处构造>()。h:120 0x7ffff7ba3b67
std::alloctor_traits>::_S_construct>()在alloc_traits.h:254 0x7ffff7ba3977
std::allocator_traits>::construct>()在alloc_traits.h:393 0x7FF7BA377
问题出现在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)
);
//...
}
请提供一个。这里不可能说有什么错-除了关于滥用unique\u ptr
(使用值)。不要使用异常规范,因为它不推荐使用。请改用noexcept
说明符。必须初始化引用成员dataset
。您有理由相信dataset.getProperties()
不是空的吗?正如@aschepler所说。这里有一个链接。如果你们中的任何一位将发布一个关于空引用的答案,那么我可以接受它作为最佳答案,因为你们的线索足以帮助我追踪这个问题。事实上,getProperties()返回了一个空对象。