【问题标题】:Passing objects in C++ understanding the basics在 C++ 中传递对象了解基础知识
【发布时间】:2018-02-22 18:11:58
【问题描述】:

您好,我正在尝试了解在 C++ 中传递对象的基础知识,并且我了解当将对象传递给函数时,会调用该对象的复制构造函数,如果函数返回一个对象,则会调用移动构造函数回归主线。我也理解如果一个对象超出范围,它们会被析构函数破坏。但是,我的程序中似乎有一个额外的析构函数。

输出:

Top of Program
Constructors here
Constructor
Constructor
End of Constructors
BoxSendReturn function
Copy Constructor
Inside BoxSendReturn
Move Constructor
Move Assignment
Destructor
Destructor
Destructor
End of Box Send Return
Destructor
Destructor

代码如下:

enter code here
#include<iostream>
using namespace std;
class Box{
   private:
   public:
      Box(){ cout<<"Constructor"<<endl; }
      ~Box(){ cout<<"Destructor"<<endl; }
      Box (const Box &other) { cout<<"Copy Constructor"<<endl; }
      Box (Box &&other) { cout<<"Move Constructor"<<endl; }
      Box operator=(const Box &other){ cout<<"Copy Operator"<<endl; }
      Box operator=(Box &&other){ cout<<"Move Assignment"<<endl;}
};

Box BoxSendReturn(Box b){
    cout<<"Inside BoxSendReturn"<<endl;
    return b;
}

int main(){
   cout<<"Top of Program"<<endl;
   cout<<"Constructors here"<<endl;
   Box b1, b2;
   cout<<"End of Constructors"<<endl; 
   cout<<"BoxSendReturn function"<<endl;
   b1 = BoxSendReturn(b2);
   cout<<"End of Box Send Return"<<endl;
   return 0;
}

【问题讨论】:

  • 您的程序中有 UB,您的分配运算符不返回任何内容,顺便说一句,它们通常返回引用,而不是按值
  • 除了未定义的行为之外,如果您在输出语句中显示this 的值,而不仅仅是正在执行的操作,将会更有帮助。这样你就会知道创建/销毁哪个对象,以及以什么顺序。
  • 感谢您解决了问题!

标签: c++


【解决方案1】:

您的代码具有未定义的行为:

  Box operator=(const Box &other){ cout<<"Copy Operator"<<endl; }
  Box operator=(Box &&other){ cout<<"Move Assignment"<<endl;}

按签名的赋值运算符必须按值返回对象,但它们错过了return 语句。如果您修复 ctors 和 dtors 的计数将匹配: live code

顺便说一句:赋值运算符通常返回引用。他们不必这样做,但这样赋值运算符具有与嵌入式类型相同的行为(返回左值等),并且没有理由进行额外的复制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多