3

我无法使用 g++ 4.1.2 编译以下代码:

#include <memory>

class A
{
    public:
};

std::auto_ptr<A> GetA()
{
    return std::auto_ptr<A>(new A);
}

class B
{
    B(std::auto_ptr<A>& pA)
    {
    }
};

class C : public B
{
    C() : B(GetA())
    {
    }
};

我得到:

将类型的右值表达式无效std::auto_ptr<A>转换为类型std::auto_ptr<A>&

问题是我无法定义变量并传递它的引用,因为我在初始化列表中。

当我只被允许改变班级时,我该怎么做C

4

2 回答 2

3

如果您只能更改 C,则可以执行以下操作:

class C: public B
{
    explicit C(std::auto_ptr<A>& pA) : B(pA) {}

public:
    static C *GetC()
    {
        std::auto_ptr<A> pA = GetA();
        return new C(pA);
    }
};

问题是试图将非常量引用绑定到由GetA. 如果您可以先将其分配给变量,则您有一个左值并且它可以正常工作。

作为亚历克斯 B说(删除答案),如果可以改变B,最好auto_ptr按值取那个论点;如果您可以更改编译器,最好使用unique_ptr和移动语义。

于 2012-02-07T11:53:11.603 回答
0

取决于 B 对传入的引用做了什么。

  • 如果 B 要获取参数的副本,则将参数设为 const &
  • 如果 B 将持有对参数的引用,那么您需要传入的任何内容都具有比 B 的实例化更长的生命周期。(如前所述,调用 GetA() 创建的临时变量不会。)
于 2012-02-07T12:22:17.303 回答