如何构造接收引用参数的基类?
我无法使用 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 typestd::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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只能更改C,则可以执行以下操作:
问题是尝试将非常量引用绑定到
GetA
返回的临时值。如果您可以先将其分配给变量,那么您就有了一个左值并且它可以正常工作。正如 Alex B
says所说(已删除答案),如果您可以更改 B,最好按值获取auto_ptr
参数;如果您可以更改编译器,最好使用unique_ptr
并移动语义。If you can only change C, you could do something like:
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
sayssaid (deleted answer), if you can change B, it would be better to take thatauto_ptr
argument by value; and if you can change compiler, it would be better to useunique_ptr
and move semantics instead.取决于 B 如何处理传入的引用。
Depends on what B does with the passed in reference.