C ++ - 在模板中定义复制构造函数

时间:2016-02-09 00:05:01

标签: c++ templates

我是模板编码的初学者,在模板中定义构造函数时遇到了问题,只是找了相关的答案,却找不到相关的问题。

基本上,类/结构xpair类似于pair firstsecond

template <typename First, typename Second>
struct xpair {
   First first{};
   Second second{};

   xpair(){}
   xpair (const First& first, const Second& second):
              first(first), second(second) {}

   xpair& operator() (const First& first_, const Second& second_) {
      return new xpair (first_, second_);
   }

   xpair& operator= (const xpair& that) {
      return new xpair (that.first, that.second);
   }
};

当我想写一些像

这样的东西时
xpair<string, string> a, b;
a = b;

它给出错误

non-const lvalue reference to type
'xpair<std::__1::basic_string<char>, std::__1::basic_string<char> >'
cannot bind to a temporary of type 'xpair<std::__1::basic_string<char>,
std::__1::basic_string<char> > *'

我尝试重写

return new xpair (that.first, that.second);

return new pair (const_cast<First&>(that.first), const_cast<First&>(that.second));

但它不起作用。问题出在哪里?

1 个答案:

答案 0 :(得分:4)

放弃new。这不是Java!

在C ++中,new是动态分配的关键字(评估指针),你没有使用它。

您还必须重新考虑返回引用语义,因为您将返回对局部变量的引用。这使得悬空引用。

事实上,你的语义总体上看起来很奇怪。例如,为什么operator=实际上没有修改分配给的对象?您应该从that分配给*this的成员,然后返回对*this的引用(或至少返回void)。

我不知道你的operator()应该做什么 - 那应该是构造函数吗?嗯,不,你已经有了其中一个...... :(

我强烈建议您查看一些运算符重载的示例,以便更好地理解C ++的构造和约束,以及我们的习语和首选语义。

相关问题