【发布时间】:2011-05-24 02:13:40
【问题描述】:
我有一个带有模板构造函数的类,用于隐式移动转换,但是这个构造函数不应该用于该类(它应该只能是可复制构造的)。但是,编译器总是尝试使用模板化构造函数而不是常规的复制构造函数。
例如有了这个,我得到了以下编译器错误,link。 (如果您想尝试,可以复制粘贴此代码)
struct implementation{};
class my_class
{
my_class(my_class&&); // delete move-constructor... OUCH... COMPILER ERROR
public:
my_class(){}
my_class(const my_class& other) : impl_(other.impl_){}
template<typename T>
my_class(T&& impl) : impl_(std::make_shared<T>(std::move(impl))){} // Still tries to use this...
private:
std::shared_ptr<implementation> impl_;
};
class other_class
{
public:
my_class foo()
{
return instance_; // Wants to use move-constructor???
}
private:
my_class instance_;
};
有人知道如何正确解决这个问题吗?
【问题讨论】:
-
你有参考,要参考吗? o_O
-
称为右值引用,见artima.com/cppsource/rvalue.html。
-
是的,
&&现在的意思是“逻辑和”。 “右值引用”,取决于上下文。令牌回收不是很棒吗? :) -
这不是 C++0x 的特性吗?我在标签中没有看到 C++0x。
-
@Pawel:好点,已编辑标签。
标签: c++ templates constructor c++11 copy-constructor