当我编译这段代码时:
class Base { /*...*/ };
class Derived : public Base { /*...*/ };
class C
{
public:
template<typename T>
C(T const& inBase) : baseInC(new T(inBase)) { /*...*/ }
template<typename T>
C(T&& inBase) : baseInC(new T(std::move(inBase))) { /*...*/ }
std::unique_ptr<Base> baseInC;
};
int main()
{
Base base;
Derived derived;
C ca(base);
C cb(derived);
C cc( (Base()) );
C cd( (Derived()) );
return 0;
}
我收到编译器消息:
In instantiation of C::C(T&&) [with T = Base&]': required from C ca(base); error: new cannot be applied to a reference type
In instantiation of C::C(T&&) [with T = Derived&]': required from C cb(derived); error: new cannot be applied to a reference type
看起来C ca(base);
与右值引用 ctor 调用相关联。为什么编译器难以将此行与第一个 ctor 关联?如果我注释掉有问题的行,构造cc
和工作将按预期进行。cd