c++ - 重载 operator= 时出现 SIGSEGV 错误

标签 c++ class operator-overloading

    _3DTocka operator=(_3DTocka _3D){
        swap(*this, _3D);
        return *this;
    }

//main()
_3DTocka _3Dx1(5, 9, 2), _3Dx2(_3Dx1); // first one is using constructor, second one copy constuctor and they both have 5,9,2
_3Dx1 = _3Dx2;

_3DTocka 是类的名称。代码编译,然后程序在运行时立即给出 SIGSEGV 错误。IDE 转到 move.h,第 167 行,代码:swap(_Tp& __a, _Tp& __b)

最佳答案

这是一个无限递归。函数 swap() 的工作原理如下:

void swap(Type & a, Type & b) {
    Type tmp = a;   \
    a = b;          -> here it calls your operator=  
    b = tmp;        /
}

您必须将 _3D 中的所有类属性分配给此

this->a = _3D.a;
this->b = _3d.b;
...

或者您可以使用 memcpy(this, &_3D, sizeof(_3D)),但前提是您的类不包含其他对象,而只包含基本类型。

关于c++ - 重载 operator= 时出现 SIGSEGV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23362794/

相关文章:

c# - 在 C# 中重载函数调用运算符

c++ - 无法在 Visual Studio 2010 中加载 libcef 符号

c++ - 使成员函数中的静态变量独立于每个实例

java - Scala 相当于 Java java.lang.Class<T> 对象

class - Scala REPL "error: value > is not a member of type parameter T"

c++ - 我可以重用右值引用参数来返回右值引用吗?

c++ - Magick++ 不读取图像

C++ 对象创建和内存分配

c++ - 通过存储用户选择的索引值实现 QDialogBu​​ttonBox

c++ - 为什么 'this' 指针在通过引用返回以进行运算符赋值时被取消引用?