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

标签 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));

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

最佳答案

删除 new。这不是 Java!

在 C++ 中,new 是您未使用的动态分配(评估为指针)的关键字。

您还必须重新考虑按引用返回的语义,因为您将返回对局部变量的引用。这会产生一个悬挂引用。

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

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

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

关于C++ - 在模板中定义复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281670/

相关文章:

c++ - 计算着色器管道创建崩溃

c++ - shared_ptr 的多个类内部 typedef

c++ - X x(t...) 是否会导致带有令人烦恼的解析的函数声明?

c++ - 为什么 C++ 编译器选择错误的函数(模板)

c++ - 在 C++ 中, "Template and Inline are orthogonal"是什么意思?

c++ - 如何将 std::unordered_multimap<uint, T> 转储到 std::vector<T>?

c++ - 姿势独立的人脸检测

c++ - WCOUT 和 COUT 中未打印的 ASCII 字符

c++ - 没有 OpenGL 的 Linux 基本图形编程

c++ - 提供 `std::complex` 时如何避免嵌入 `T=std::complex<Q>` ?