What is wrong with this struct X in C++ code?

2019-08-20 03:59发布

问题:

I got this question as a homework assignment. It compiled and ran as expected and yet I'm supposed to find something wrong with it, though nothing to do with the const.

I know this is a struct so my variables are all public - that is not the problem. I thought perhaps it is related to the "new" used in the constructor. I would love to hear your thoughts.

struct X
{
    explicit X(int);
    ~X();
    void Foo();
    void Bar() const;

    int m_a;
    int *m_p;
};

X::X(int a_): m_a(a_), m_p(new int(a_)){}
X::~X()
{
    delete m_p;
    m_p = NULL;
}

void X::Foo()
{
    ++m_a;
    --(*m_p);
}

void X::Bar() const
{
    std::cout<<m_a<<std::endl;
    std::cout<<*m_p<<std::endl;
    std::cout<<m_p<<std::endl;
}

void Fifi(const X& x_)
{
    x_.Bar();
}

int main (void)
{
    X x1(1);
    x1.Foo();
    Fifi(x1);
    return 0;
}

回答1:

Your class violates the rule of three.

Exactly as written it doesn't do anything bad, but seemingly harmless constructs involving X may cause mysterious errors (due to various forms of undefined behaviour).

X a(1), b = a;

On my machine the above line causes

*** Error in `./a.out': double free or corruption (fasttop): 0x0000000000dfec20 ***


标签: c++ class struct