gpt4 book ai didi

c++ - unique_ptr 在指向对象上调用 operator[]() 时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:45 25 4
gpt4 key购买 nike

我正在努力解决一个令人讨厌的运行时错误。要发布的代码有点多,但我希望阅读量不要太多,诊断问题也不要太少。出于某种原因,当我引用它并使用运算符函数调用时,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() 中爆炸:

Thread [1] 14303 [core: 10] (Suspended : 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 0x7ffff7bbb762 bmd2::PropertyCollection::operator at PersistentObject.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
<...more frames...>

最佳答案

问题出在您的 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)
);
//...
}

关于c++ - unique_ptr 在指向对象上调用 operator[]() 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com