【问题标题】:Comparing Auto and Reference type in C++比较 C++ 中的自动和引用类型
【发布时间】:2014-01-25 13:10:52
【问题描述】:

试图比较 Auto 变量与 Object 引用变量 并且程序在主端被击中。这是因为*ip 但我无法理解构造函数/析构函数调用以及为什么在auto objA = objR; 时不创建新对象 我写的代码如下:

#include <iostream>
#include <string>
using namespace std;

typedef class auto_type_test
{
    string name;
    int age; int * ip; 
public:
    auto_type_test(const char* _name, int _age) : name(_name),age(_age){cout << "Constructor called"<<endl;ip= new int[2];}
    auto_type_test() {}
    ~auto_type_test() {cout << "Destructor called"<<endl;delete []ip;}
    friend ostream& operator <<(ostream& out, const auto_type_test& obj);
}MYtest;

ostream& operator <<(ostream& out, const MYtest& obj)
{
    out << "Name:"<<obj.name<<" Age:"<<obj.age<<endl;
    out << obj.ip[0] <<endl; // int pointer to test that auto variable not created  
    return out;
}

int main()
{
    MYtest obj("OriginalObject",26);
    MYtest& objR = obj;
    auto objA = objR;
    cout << obj << objR << objA << endl;
    objR = MYtest("refmodified",1);        //<line1>Commenting this and below line 
    //objA = MYtest("automodified",2);     //<line2>alternatively
    cout << obj << objR << objA << endl;
    return 0;
}

当 Line1 评论输出时:

Constructor called
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451

Constructor called
Destructor called
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Name:automodified Age:2
-17891602

Destructor called

当 Line2 评论输出时:

Constructor called
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451

Constructor called
Destructor called
Name:refmodified Age:1
-17891602
Name:refmodified Age:1
-17891602
Name:OriginalObject Age:26
-842150451

Destructor called
Destructor called

【问题讨论】:

标签: c++ constructor reference destructor auto


【解决方案1】:

这里发生的事情不是很明显吗?在auto objA = objR; 行中,您的objA 变量不是推导出为MyTest&amp;,而是推导出为MyTest,因此成为从您的obj 构造的副本(因为objR 只是对它的引用)。您没有看到任何输出,因为您还没有实现由编译器自动为您提供的复制构造函数。

如果你现在打电话

objR = MYtest("refmodified",1);

您的原始对象已被修改(调用了赋值运算符),但您的副本 (objA) 保持不变。

如果你打电话,反过来

objA = MYtest("automodified",2);

您的副本已修改,但您的原始对象保持不变。


要实现您想要实现的目标(objA 是对 obj 的引用),您必须像这样声明它:

auto& objA = objR;

【讨论】:

  • 感谢@Paranaix 一些非常基本的概念得到了澄清
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
相关资源
最近更新 更多