基类中的运算符定义

时间:2012-02-17 05:14:31

标签: c++ inheritance

我有以下示例代码。 class bar派生自基类foo,并为ptr_x分配内存,同时通过基类授予读/写访问权限。这是一个大型代码的玩具模型,其中读/写函数对于对象的所有不同变体是相同的,但是内存分配在不同的变体中略有不同。

#include <iostream>

class foo{
protected:
    int *ptr_x;

public:
    foo(){
        std::cout << " 1) Inside foo constructor: " << ptr_x << std::endl;
    }

    void read() 
    {
        std::cout << " 2) Inside read function: " <<  ptr_x << std::endl;    
        std::cout << " 3) Inside read function: " << *ptr_x << std::endl;
    }
    void operator=(const int rhs)
    {
        std::cout << " 4) Inside operator= : " <<  ptr_x << std::endl;
        *ptr_x = rhs;
    }        
};
class bar: public foo{

public:
    bar(int a)
    : foo()
    {
        std::cout << " 5) Inside bar constructor: " << ptr_x << std::endl;
        ptr_x = new int;
        std::cout << " 6) Inside bar constructor: " << ptr_x << std::endl;
        *ptr_x = a;
    }
    ~bar()
    {
        std::cout << " 7) Inside bar destructor: " << ptr_x << std::endl;
        if (ptr_x != NULL) {delete ptr_x; ptr_x = NULL;}
    }
};
int main (){
    bar a(20);
    a.read();
    a = 40;
    a.read();
    return 0;
}

当我运行代码时,我得到:

 1) Inside foo constructor: 0
 5) Inside bar constructor: 0
 6) Inside bar constructor: 0x1d8f010
 2) Inside read function: 0x1d8f010
 3) Inside read function: 20
 1) Inside foo constructor: 0x7f40c11e3b68
 5) Inside bar constructor: 0x7f40c11e3b68
 6) Inside bar constructor: 0x1d8f030
 7) Inside bar destructor: 0x1d8f030
 2) Inside read function: 0x1d8f030
 3) Inside read function: 0
 7) Inside bar destructor: 0x1d8f030
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0000000001d8f030 ***

我有以下问题:1)为什么代码不在基类中输入operator=? 2)为什么第二次调用构造函数/析构函数? 3)为什么会出现double free问题?

我在这里做错了什么?

编辑:Ok double free问题很明显,但为什么有两个相同内存位置的实例?这在某种程度上与operator=有关,因为当我评论它时一切都很好。

由于

2 个答案:

答案 0 :(得分:2)

观察行为的推理:

编译器在派生类

中使用转换构造函数
  bar(int a)

用于评估:

  a = 40;

它接受整数40并使用转换构造函数创建bar对象,然后使用隐式复制赋值运算符将创建的bar对象分配给a=)由编译器为类bar生成。

这就是您看到对bar构造函数的其他调用以及从不调用Base类重载=的原因。此外,双重自由的原因在于,您有多个bar对象,这些对象一直指向为ptr_x分配的动态内存,当其中一个对象超出范围时,将调用析构函数,从而解除分配内存但使其他对象成员指针处于悬空状态。

如何解决这些问题:
如果您不希望编译器将其用于此类隐式转换,则应标记转换构造函数 explicit

您应该按照课程bar Rule of Three 进行操作。

<强>警告:
请注意,基类中的=运算符始终由派生类的隐式生成的=运算符隐藏。

答案 1 :(得分:1)

对于你应该宣布的第一个问题  bar (int a)

explicit bar(int a).

这给出了一个正确的编译错误,即类栏应该有=运算符定义。