C++代码中的这个结构 X 有什么问题

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

本文关键字:什么 问题 结构 代码 C++      更新时间:2023-10-16

我把这个问题作为家庭作业。它按预期编译并运行,但我应该发现它有问题,尽管与 const 无关。

我知道这是一个结构,所以我的变量都是公共的 - 这不是问题。我想也许这与构造函数中使用的"新"有关。我很想听听你的想法。

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;
}

你的类违反了三法则。

正如所写的那样,它并没有做任何坏事,但涉及X的看似无害的结构可能会导致神秘的错误(由于各种形式的未定义行为)。

X a(1), b = a;

在我的机器上,上述行导致

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