简体   繁体   English

当C ++匿名对象替换先前分配的对象时会发生什么?

[英]What happens when a C++ anonymous object replaces previously assigned object?

This question concerns what happens to an object when a variable is assigned to a new object. 这个问题与将变量分配给新对象时对象发生什么情况有关。

Date {
    public:
        Date(int day, int month);
        int day;
        int month;
};

in main: 在主要方面:

Date birthday(7,4); //line 1
birthday = Date(5,5); //line 2

My understanding is that line 2's RS returns an anonymous object. 我的理解是第2行的RS返回一个匿名对象。 My question is, what happens to the object that was created with the values 7,4? 我的问题是,用值7,4创建的对象会怎样? Is it replaced in memory by the anonymous object? 它在内存中被匿名对象取代了吗?

You cannot replace some object with another. 不能将某个对象替换为另一个。

What you can do, and what actually happens in your example, is move-assigning from a temporary object to some target-object. 可以做的事,以及在示例中实际发生的事,是将分配从临时对象移动到某些目标对象。

If it was not a temporary object, move-assigning from it would not happen, instead copy-assigning would take place. 如果它不是临时对象,则不会发生从其进行移动分配,而是进行复制分配。

Neither changes which object it is, only what value it has. 两者都不会更改其对象,只会更改其具有的值。

BTW: Copy-assignment, Move-assignment, copy-construction, move-construction and destruction for your example-class are implicitly defined as member-by-member. 顺便说一句:示例类的复制分配,移动分配,复制构造,移动构造和销毁隐式定义为每个成员。

暂无
暂无

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

相关问题 在C ++中重新分配对象变量时,原始对象会发生什么? - When object variable is reassigned in C++, what happens to the original object? 如果将匿名对象传递给需要引用的函数,C ++中会发生什么? - What happens in C++ if you pass an anonymous object into a function that takes a reference? c ++中的对象调用不带参数的成员函数时会发生什么 - What happens when a member function with no arguments is called by an object in c++ 通过赋值初始化C ++对象时会发生什么? - What happens when you initialize a C++ object by assignment? 在C ++中为对象分配引用的值时会发生什么? - What happens when I assign an object the value of a reference in C++? C++ 在构造函数中将 0 分配给类变量时会发生什么 - C++ what happens when 0 is assigned to class variable in constructor ARC和C ++对象中的Objective C对象会发生什么? - What happens with ARC and an Objective C object inside a C++ object? 如果未分配返回未定义对象类型引用的C ++函数的返回值,会发生什么? - What should happen when the return value from a C++ function that returns a reference of an undefined object type is not assigned? 当我们在C ++中重新初始化对象时会发生什么,我非常困惑 - very confused about what happens when we reinitialize the object in c++ 当我通过引用传递一个对象并且它超出范围时,C ++会发生什么? - What happens in C++ when I pass an object by reference and it goes out of scope?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM