c++ - 初始化引用的 shared_ptr ( std::tr1::shared_ptr<class&> )

标签 c++ reference shared-ptr

我正在使用一个返回对我的引用的库。
我需要将此引用用作类属性。
无法直接在构造函数中初始化属性(之前需要初始化库),我考虑使用 shared_ptr 进行延迟初始化:

#include <iostream>
#include <string>
#include <tr1/memory>

//This is library, cannot touch
std::string globalString = "TEST";
std::string& getStringReference()
{
    return globalString;
}

//this is my class which uses the library
class Foo
{
public:
    Foo() :
        testString_( std::tr1::shared_ptr< std::string& >() )
    {
        //do some initialization of the library here...
        //now init the shared_ptr
        testString_.reset( getStringReference() );
    }

    std::string getString() const
    {
        return *testString_;
    }

private:
    std::tr1::shared_ptr< std::string& > testString_;
};

//and a main to be compilable and check if the above works...
int main()
{
    Foo foo;
    std::cout << foo.getString() << std::endl;
}

但不幸的是,这不起作用。 g++ 给出这样的消息:

error: forming pointer to reference type ‘std::string&’

我尝试了一些其他方法来将引用获取到 shared_ptr 中,但没有任何效果......也许你可以给我一个提示。

注意:
- 在“真实世界”而不是 std::string 中,数据类型是一个没有默认构造函数的类。
- 对于那些仍然想知道的人:以上只是一个简化的示例代码:)

更新:
- 在尝试应用这些建议时,我发现与示例中使用的 std::string 相反,我的类有一个私有(private)复制构造函数。这意味着我无法将对象复制到新对象中。

最佳答案

如果您仅由引用提供,则意味着您不负责内存管理,这反过来意味着您不能使用自己的内存管理。也就是说,您不应使用任何类型的智能指针来保存该对象。

虽然您可以使用 & 运算符获取真实对象的地址,但是当您的 shared_ptr 超出范围并试图释放内存,库本身会尝试自行释放内存。

关于c++ - 初始化引用的 shared_ptr ( std::tr1::shared_ptr<class&> ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459000/

相关文章:

c++ - 检测几乎为零并将它们替换为 0.0 或将它们保留为小数字是否更快?

javascript - 为什么没有官方 JavaScript 引用?

mongodb - 设计 mongodb 模式使用嵌入还是引用?

c++ - `weak_ptr::expired` 对象 dtor 中的行为

c++ - 如何在 Qt 小部件应用程序中翻译来自外部文件的字符串?

c++ - 通过两个类时出现奇怪的输出数据

c# - 基于常量的 Visual Studio 条件项目引用

c++ - 如何将 boost::shared_ptr 引入现有(大型)C++ 代码库?

c++ - 出现 'bad_weak_ptr' 错误

c++ - 如何为 libsvm 创建训练数据(作为 svm_node 结构)