比较C ++中的Auto和Reference类型

时间:2014-01-25 13:10:53

标签: c++ constructor reference destructor auto

试图将自动变量与对象引用变量进行比较,程序在主端被攻击。它是因为*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

1 个答案:

答案 0 :(得分:0)

这显然发生了什么?在第auto objA = objR;行中,您的objA变量不会推断为MyTest&,而是MyTest,因此会从objobjR构建副本只是对它的引用)。您没有看到任何输出,因为您没有实现编译器为您自动提供的复制构造函数。

如果你现在打电话

objR = MYtest("refmodified",1);

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

如果你打电话

,反之亦然
objA = MYtest("automodified",2);

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


要做你想要实现的目标(objA作为对obj的引用),你必须这样声明:

auto& objA = objR;