小编Pas*_*rly的帖子

如何在一个必须复制构造的类中使用std :: auto_ptr?

我有foo一个包含std :: auto_ptr成员的类,我想复制构造,但这似乎不允许.作业有类似的东西.请参阅以下示例:

struct foo
{
private:
    int _a;
    std::string _b;
    std::auto_ptr< bar > _c;

public:
    foo(const foo& rhs)
        :   _a(rhs._a)
        ,   _b(rhs._b)

        ,   _c(rhs._c)
                // error: Cannot mutate rhs._c to give up ownership - D'Oh!
    {
    }

    foo& operator=(const foo& rhs)
    {
         _a = rhs._a;
         _b = rhs._b;

         _c = rhs._c;
             // error: Same problem again.
    }
};
Run Code Online (Sandbox Code Playgroud)

我可以声明_c,mutable但我不确定这是否正确.有没有人有更好的解决方案?

编辑

好吧,我没有得到我期待的那种答案,所以我会对这个问题有所了解.

  • 类型的对象foo在堆栈上创建,并通过值传递到容器类(而不是stl),然后超出范围.我对容器代码没有任何控制权.(它实际上是一个活动的队列实现,有bug.)
  • bar班是一个相当重量级的解析器.它的性能非常差new,delete因此即使它是可复制的,也会太昂贵.
  • 我们可以保证在bar …

c++ smart-pointers auto-ptr

8
推荐指数
2
解决办法
6921
查看次数

标签 统计

auto-ptr ×1

c++ ×1

smart-pointers ×1