C ++代码中的这个struct X有什么问题? [英] What is wrong with this struct X in C++ code?

查看:91
本文介绍了C ++代码中的这个struct X有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

您的课程违反了三个规则


完全按照书面规定它并没有什么坏处,但是涉及 X 的看起来无害的构造可能会导致神秘的错误(由于各种形式的不确定行为)。

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 ++代码中的这个struct X有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆