samedi 28 mars 2020

Segmentation fault after returning unique_ptr inside of pair from function

I have a factory that creates class instances from strings. KeyValueType is an abstract class, which will be passed to Map/Reduce functions.

class KeyValueType {
public:
    virtual void parse(const std::string &) = 0;

    virtual std::string to_string() const = 0;
};

Factories in code are getting from the shared library (to be able to config map/reduce functions from a remote computer).

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;
};

So, I have the next code, where I'm creating two objects key/value and returning them, as a pair of 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;
}

The actual problem is, that in blocking_get_result() function key and value are valid and virtual function to_string() is working correctly, but after returning pair from function to main unique_ptr is not null, but to_string throws Segmentation Fault. Also, dynamic_cast to a derived class is causing Segfault.

Aucun commentaire:

Enregistrer un commentaire