如何构造接收引用参数的基类?

发布于 2025-01-03 04:45:57 字数 567 浏览 4 评论 0原文

我无法使用 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 类型的右值表达式强制转换为 std::auto_ptr& 类型无效

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

当我只被允许更改类 C 时,我该如何做到这一点?

I can't compile the following code using 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())
    {
    }
};

I get:

invalid cast of an rvalue expression of type std::auto_ptr<A> to type std::auto_ptr<A>&

The problem is I can't define a variable and pass its reference because I am inside a initialization list.

How can I do that when I am only allowed to change class C?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天冷不及心凉 2025-01-10 04:45:58

如果您只能更改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返回的临时值。如果您可以先将其分配给变量,那么您就有了一个左值并且它可以正常工作。

正如 Alex B says 所说(已删除答案),如果您可以更改 B,最好按值获取 auto_ptr 参数;如果您可以更改编译器,最好使用 unique_ptr 并移动语义。

If you can only change C, you could do something like:

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);
    }
};

The problem is trying to bind a non-const reference to the temporary returned by GetA. If you can assign that to a variable first, you have an lvalue and it works ok.

As Alex B says said (deleted answer), if you can change B, it would be better to take that auto_ptr argument by value; and if you can change compiler, it would be better to use unique_ptr and move semantics instead.

十二 2025-01-10 04:45:58

取决于 B 如何处理传入的引用。

  • 如果 B 要获取参数的副本,则将参数设置为 const &
  • 如果 B 要保存对参数的引用,那么您需要传入的任何内容都具有比 B 的实例化更长的生命周期。(如前所述,通过调用 GetA() 创建的临时变量则不需要。)

Depends on what B does with the passed in reference.

  • If B is going to take a copy of the argument, then make the argument a const &
  • If B is going to hold a reference to the argument then you need whatever is passed in to have a longer lifetime than the instantiation of B. (As mentioned already, the temporary created by a call to GetA() doesn't.)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文