我有一个工厂,可以从字符串创建类实例。 KeyValueType是一个抽象类,它将被传递给Map / Reduce函数。
class KeyValueType {
public:
virtual void parse(const std::string &) = 0;
virtual std::string to_string() const = 0;
};
代码工厂是从共享库获取的(以便能够从远程计算机配置映射/归约功能)。
std::unique_ptr<KeyValueType> KeyValueTypeFactory::create() override {
return std::make_unique<KeyValueType<T>>();
};
std::unique_ptr<KeyValueType> KeyValueTypeFactory::create(const std::string &str) override {
std::unique_ptr<KeyValueType> ptr = this->create();
ptr->parse(str);
return ptr;
};
所以,我有下一个代码,其中我将创建两个键/值对象并将它们作为一对unique_ptr返回
std::pair<std::unique_ptr<KeyValueType>, std::unique_ptr<KeyValueType>>
get_key_value_from_json(const std::string &data, std::unique_ptr<KeyValueTypeFactory> &key_factory, std::unique_ptr<KeyValueTypeFactory> &value_factory) {
boost::property_tree::ptree pt{};
boost::property_tree::json_parser::read_json(dynamic_cast<std::stringstream &>(std::stringstream{} << data), pt);
return { std::move(key_factory->create(pt.get("key", ""))),
std::move(value_factory->create(pt.get("value", ""))) };
}
std::pair<std::unique_ptr<KeyValueType>, std::unique_ptr<KeyValueType>> blocking_get_result() {
... // Get json and config
auto[key, value] = get_key_value_from_json(json, cfg->key_out_factory, cfg->value_res_factory);
std::cout << "The result of Map/Reduce is " << value->to_string() << std::endl;
return { std::move(key), std::move(value) };
}
int main() {
auto[key, value] = blocking_get_result();
std::cout << (value.get() == nullptr) << std::endl;
std::cout << "The result of Map/Reduce is " << value->to_string() << std::endl;
return 0;
}
实际的问题是,在
blocking_get_result()
中,功能键和值有效,并且虚拟功能to_string()
正常工作,但是从功能返回键对后,主unique_ptr
不为空,但是to_string
引发了Segmentation Fault。同样,对派生类的dynamic_cast
也会导致Segfault。
最佳答案
实际的问题是,使用dlopen
和dlsym
完成配置并将结果包装到shared_ptr中。因此,共享库在blocking_get_result中被释放。因此在vtable中的主指针变为无效。
关于c++ - 从函数返回对内的unique_ptr后的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60899269/