c++ - 为什么我不能从函数返回 Boost::Scoped_ptr?

标签 c++ boost smart-pointers scoped-ptr

所以我尝试围绕 boost.extension 函数创建一些包装器来创建类。所以我创建了一个函数:

template <class BaseClass, class ConstructorType>
 boost::scoped_ptr<BaseClass> get_class (shared_library & lib, std::string class_name, ConstructorType value ) {
map<string, factory<BaseClass, ConstructorType> > lib_factories = get_factories<BaseClass, ConstructorType>(lib);
return boost::scoped_ptr<BaseClass> lib_class(lib_factories[class_name].create(value));
}

调用:

template <class BaseClass, class ConstructorType>
map<string, factory<BaseClass, ConstructorType> > get_factories (shared_library & lib) {
    type_map lib_types;
    if (!lib.call(lib_types)) {
        cerr << "Types map not found!" << endl;
        cin.get();
    }

    map<string, factory<BaseClass, ConstructorType> > lib_factories(lib_types.get());
    if (lib_factories.empty()) {
        cerr << "Producers not found!" << endl;
        cin.get();
    }
    return lib_factories;
}

但最后一个并不是那么重要。重要的是 - 我无法获得我的函数 return=(

我尝试这样:

boost::scoped_ptr<PublicProducerPrototype> producer = get_class<PublicProducerPrototype, int>(simple_producer, "simpleProducer", 1);

我也试过:

boost::scoped_ptr<PublicProducerPrototype> producer ( get_class<PublicProducerPrototype, int>(simple_producer, "simpleProducer", 1));

但编译器告诉我 C2248它不能调用 boost::scoped_ptr<T> 的一些私有(private)成员

那么如何使我的返回...可返回//如何接收?

最佳答案

boost::scoped_ptr 是不可复制的。因为您不能复制 scoped_ptr,所以您也不能返回一个(按值返回一个对象要求您能够复制它,至少在 C++03 中是这样)。如果需要返回智能指针拥有的对象,则需要选择不同类型的智能指针。

如果您的编译器支持 std::unique_ptr,您应该改用它(因为看起来您使用的是 Visual C++,Visual C++ 2010 支持 std::unique_ptr );否则,请考虑使用 std::auto_ptr{std,std::tr1,boost}::shared_ptr,具体取决于您的具体用例。

关于c++ - 为什么我不能从函数返回 Boost::Scoped_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724119/

相关文章:

c++ - std::unordered_map::emplace 对象创建

python - C++ wxsocket TCP服务器发送无符号字符数组但python客户端在中获得4个字节

c++ - 将类放入 unique_ptr 后立即释放

c++ - 自动实例化的智能指针

c++ - 将 const unique_ptr 引用作为参数传递

c++ - 为什么在gcc中进行静态初始化之前要进行动态初始化

java - 如何通过 JNI 获取普通的一维数组而不是二维数组?

c++ - 在 unordered_map 中放置一个结构,引用问题

c++ - 在没有 chrono 的 Windows 上使用 C++ 获取以纳秒为单位的时间

c++ - boost::iostream bzip2_decompressor 不解压缩由 bzip2_compressor 压缩的文件