简体   繁体   English

调用重载赋值 function 时向量未正确重新初始化

[英]Vectors not reinitialized properly when calling overloaded assignment function

I have a class "SecretMessages" that utilizes operator overloading with both copy and assign.我有一个 class “SecretMessages”,它利用复制和分配的运算符重载。 It has 3 data members, most importantly a vector messages, and a vector message_views which corresponds to the number of remaining views of each message.它有 3 个数据成员,最重要的是一个向量消息和一个向量 message_views,它对应于每条消息的剩余视图数。 The issue I'm having is when the assignment operator is called the vectors are not being reinitialized properly.我遇到的问题是,当调用赋值运算符时,向量没有正确重新初始化。 So even though I'm able to read all of the data being copied over just fine inside of the function, when it is called on an L value these values do not update the vector.因此,即使我能够读取 function 内部复制的所有数据,但在 L 值上调用它时,这些值不会更新向量。

My class definition looks as such:我的 class 定义如下所示:

class SelfDestructingMessage {
     public:
         vector<string> messages;
         long number_of_allowed_views;
         vector<long> message_views; // keeps track of each message view 
         ... 
         SelfDestructingMessage(SelfDestructingMessage &sdm); // copy 
         SelfDestructingMessage operator = (SelfDestructingMessage &sdm); // assign };

And here is the output from the test file I have been running, which creates a new SecretMessage object and assigns it to one that has been previously defined.这是我一直在运行的测试文件中的 output,它创建了一个新的 SecretMessage object 并将其分配给先前定义的一个。

sdm4:       //message_views print is empty before assignment
ASSIGNMENT OP
printing out message_views after assign:
0
2
1
END ASSIGNMENT
sdm4 after message views after assignment: 
0
0
0

I'm not sure why the message_views vector of sdm4 isn't updating after *this is returned even though the values 0, 1, and 2 are all in the messages vector in assignment function.我不确定为什么 sdm4 的 message_views 向量在 *this 返回后没有更新,即使值 0、1 和 2 都在分配 function 中的消息向量中。 Any ideas?有任何想法吗?

Looks like the return from your assignment is copying the object, so your return statement calls your copy constructor.看起来您的赋值返回正在复制 object,因此您的 return 语句调用您的复制构造函数。 You didn't send us that, but if it clears its argument, it's clearing *this.你没有把那个发给我们,但如果它清除了它的论点,它就会清除 *this。

Try changing the return type of the assignment operator to SelfDestructingMessage &, so that copy is not invoked.尝试将赋值运算符的返回类型更改为 SelfDestructingMessage &,以便不调用副本。

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

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