简体   繁体   English

C++中临时对象的销毁

[英]Destruction of a temporary object in C++

I have two classes: Vote and Voter .我有两个类: VoteVoter

The class Voter has a constructor that receives two strings. Voter类有一个构造函数,它接收两个字符串。

The class Vote has a constructor that receives an object from the class Voter and a string. Vote类有一个构造函数,它从Voter类接收一个对象和一个字符串。

Now, I do the following:现在,我执行以下操作:

Voter vr6("Cyprus", "Regular");
eurovision += Vote(vr6, "USA");

Where eurovision is an object from a class where I overloaded the += operator.其中 eurovision 是我重载+=运算符的类中的对象。

From what I know, in the second line a temporary Vote object will be created.据我所知,在第二行中将创建一个临时Vote对象。

My question is, how exactly is vr6 affected from the destruction of the temporary object?我的问题是, vr6究竟如何受到临时对象破坏的影响?

EDIT: The definition of the Vote constructor and destructor:编辑: Vote构造函数和析构函数的定义:

Vote(Voter current_voter, string state1, string state2 = "", string state3 = "", string state4 = "", string state5 = "", string state6 = "", string state7 = "", string state8 = "", string state9 = "", string state10 = "") :
        voter(current_voter), voted_state(new string[VOTE_ARRAY_SIZE]){
        voted_state[0] = state1;
        voted_state[1] = state2;
        voted_state[2] = state3;
        voted_state[3] = state4;
        voted_state[4] = state5;
        voted_state[5] = state6;
        voted_state[6] = state7;
        voted_state[7] = state8;
        voted_state[8] = state9;
        voted_state[9] = state10;
    }
    ~Vote() {
        delete[] voted_state;
    }

Since you pass vr6 by value to Vote 's constructor, the object in vr6 itself will not depend on the Vote object's lifetime.由于您将vr6按值传递给Vote的构造函数,因此vr6的对象本身将不依赖于Vote对象的生命周期。 Note, however, that with the "call by value" a temporary copy of vr6 will be created, and this copy will get deleted once the statement that calls Vote s constructor has ended.但是请注意,“按值调用”将创建vr6的临时副本,一旦调用Vote构造函数的语句结束,该副本将被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM