在C ++中初始化为其自身的对象 [英] Object that initializes to itself in C++

查看:81
本文介绍了在C ++中初始化为其自身的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有代码:

class test{
    public:

    test(){
        cout<<endl<<"TEST";
    }

    void another(){
        cout<<endl<<"Another";
    }

};

int main(){
    test chk = chk;
    chk.another();
}

在这里,我已经初始化了类型为<$的新创建对象c $ c> test 本身。

Here, I've done an initialization of newly created object of type test to itself.

这种初始化是否具有特殊目的,除了初始化 test chk; 而不是 test chk = chk;

Does such initialization serve special purpose, does such initialization do anything otherwise than initializing test chk; instead of test chk = chk;?

我知道如果将对象初始化为自身,则无法调用构造函数,但是为什么呢?

I understand that the constructor cannot be called if the object is initialized to itself, but why?

我想了解更多有关将对象初始化为自身的信息。

I would like to know more about such initialization of an object to itself.

推荐答案

我稍微修改了您的代码,希望您能明白这一点:

I modified your code a bit and hope you can catch the point:

class test{
    public:
        test(){ cout<<endl<<"TEST"; }

        test(const test& in)
        {   
            if ( this == &in)
            {   
                cout<<endl<<"Self init";
            }
            cout<<endl<<"Copy ctor";
        }

        void another(){ cout<<endl<<"Another"; }
};  

int main(){
    test chk = chk;
    chk.another();
    cout<<endl;
}  

如果您现在调用代码,将得到以下输出:

If you now call your code you will get the following output:

Self init
Copy ctor
Another

cout< 语句的一句话。您上次的输出是隐藏的,因为在最后的输出之后没有 endl cout 被缓冲,这意味着它只会在下一个 endl 或缓冲区已满后才写入控制台。因此最好这样写: cout<< something< endl;

One remark to your cout<<endl statements. You last output are hidden because there is no endl after the last output. cout is buffered which means here that it will only write to your console after the next endl or the buffer is full. So it is even better to write: cout<<"something"<<endl;

To代码和初始化:

如果在复制构造函数中使用输入对象的地址,则可以检查是否对自己进行复制。这是一个好习惯,因为如果分配的内存需要使用默认的构造函数进行复制,则您需要一个自己的副本构造函数。从我的示例中可以看到, this in 中的地址是相同的,这意味着复制构造函数要复制到自身,如果不通过特殊方式处理,通常是错误的!

If you take the address of the input object in your copy constructor you can check if you do a copy to yourself. That is good practice, because you need a own copy constructor if you have allocated memory which can't be copied with the default constructor. As you can see from my example, the address of this and in is the same which means the copy constructor want to copy to itself which is typically wrong if not handled in a special way!

对于您的测试用例,其行为仅仅是对象未初始化,因为您复制了未初始化的对象最终导致未初始化的对象。这永远不是您想要的,并且叮当响报警告。

For your testcase the behaviour is simply that your object is not initialized, because you copy an uninitialzed object to itself which ends up in a uninitialized object. This is never what you want and clang reports a warning.

这篇关于在C ++中初始化为其自身的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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