c++ - 从函数返回对内的unique_ptr后的段错误

标签 c++ c++11

我有一个工厂,可以从字符串创建类实例。 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。

最佳答案

实际的问题是,使用dlopendlsym完成配置并将结果包装到shared_ptr中。因此,共享库在blocking_get_result中被释放。因此在vtable中的主指针变为无效。

关于c++ - 从函数返回对内的unique_ptr后的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60899269/

相关文章:

c++ - std::string 如何管理这个技巧?

c++ - OpenCV 在 C++ 中读取 16 位 tiff 图像

c++ - 使用引用遍历链表不起作用

c++ - 优雅地从指针初始化 std::array 到缓冲区?

c++ - 将捕获的 lambda 作为函数指针传递

c++ - 获取释放内存顺序与顺序一致性不同的实际例子是什么?

c++ - `std::enable_if<std::is_compound<double>::value>` 出现意外的 SFINAE 行为

c++ - 如何知道推力::partition_copy的结果中有多少个元素

java - Java 与 C++ 中的构建器?

c++ - 寻找对我的线程安全、无锁队列实现的批评