[英]Why does C++ choose to cast my return value to int?
由于各种无聊的原因,我需要一个盒装的int类,它主要作为一个int,但是是一个继承自base的类,因此它可以与对象层次结构的其他部分一起工作。 我包含了一个构造函数,它接受一个int,以及一个int cast,所以我可以很容易地将我的盒装int与代码中的常规int混合。 但是,我看到一个非常奇怪的行为,我无法弄清楚:当我从函数返回我的盒装int时,我希望它使用我的复制构造函数来引用另一个BoxedInt。 但是,它将我的盒装int转换为int,然后使用我的int构造函数。 这会导致问题,因为在我的实际代码库中,在这种情况下我还想要复制其他基类属性,并且它们通过获取此强制转换/构造函数路径而丢失。 这是有问题的代码:
class BoxedInt
{
private:
int m_int;
public:
BoxedInt():m_int(0)
{
trace(L"Constructed with nothing");
}
BoxedInt(int val):m_int(val)
{
trace(L"Constructed with int");
}
BoxedInt(BoxedInt& val)
{
trace(L"Constructed with reference");
m_int = val.m_int;
}
operator int()
{
trace(L"Cast to int");
return m_int;
}
};
BoxedInt funky()
{
BoxedInt TempInt = 1;
return TempInt;
}
int main(int argc, char* argv[])
{
trace(L"Start");
BoxedInt test1 = 1;
trace(L"Copying");
BoxedInt test2 = test1;
trace(L"Assigning from return value");
BoxedInt test3 = funky();
trace(L"Done");
return 0;
}
运行时,这是输出:
Start
Constructed with int
Copying
Constructed with reference
Assigning from return value
Constructed with int
Constructed with reference
Cast to int
Constructed with int
Done
因此,当我将一个值分配给另一个时,使用基于引用的构造函数,正如我所期望的那样。 但是,当我将函数的返回值赋给BoxedInt时,由于某种原因,编译器决定转换为int,然后使用int构造函数。 我的C ++生疏了,我无法深入了解这个奇怪的编译器决策,我似乎无法抵消。 有任何想法吗?
您的复制构造函数接受对非const的引用,因此无法使用临时调用它。 funky()
的返回值是临时的,因此复制构造函数不能用于构造test3
。
使复制构造函数采用const引用,它应该没问题。
你的copy-constructor采用非const引用,这意味着你不能将临时绑定到参数,这正是你想要的返回方法所做的。 因此,编译器选择其他路由。
更改你的拷贝构造函数:
BoxedInt(const BoxedInt &val) {
事实上,由于BoxedInt test1 = 1;
,Clang 3.4 给出了错误 BoxedInt test1 = 1;
。
我相信问题(或其中之一)是复制构造函数签名:
BoxedInt(BoxedInt& val)
它应该是
BoxedInt(const BoxedInt& val)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.