开发者

Copy Constructor with reference variable

开发者 https://www.devze.com 2023-01-20 15:56 出处:网络
I have a class as given below, I want to write a copy constructor for the same. I开发者_JAVA技巧 need to create a deep copy constructor for this. following code is printing x and c properly but value

I have a class as given below, I want to write a copy constructor for the same. I开发者_JAVA技巧 need to create a deep copy constructor for this. following code is printing x and c properly but value of y here is garbage.

#include "stdafx.h"
#include <string.h>
class MyClass
{
public:

 MyClass(int a) : y(a) {
 }
 MyClass(const MyClass &myClass) : y(myClass.y)
 {
  x = myClass.x;
  c = new char[10];
  strcpy(c, myClass.c);
 }

  int x;
  char *c;
  int &y;

};

int _tmain(int argc, _TCHAR* argv[])
{
 MyClass m1(0);
 m1.c = new char[10];
 strcpy(m1.c, "gourav");
 m1.x = 10;
 m1.y = m1.x;

 MyClass m2 = m1;

 printf("x=%d\nc=%s\ny=%d\n", m2.x, m2.c, m2.y);
 return 0;
}


In your code, y is reference.. You're creating MyClass m1(0), so m1.y points to a temporary variable - 0. You just must not do this.. I don't know why you y member is reference.. ?? Anyway, if you want this to be that way, do that:

//..
int a = 10;
MyClass m1(a);
//..

Anyway, this is ugly.. And dangerous, if you don't know what you're actually doing.. You should really have a very good reason to do that.

Also, redesign your class, and its members' names..

So, the problem is NOT in the copy-constructor at all..


The problem is not copying, but the constructor: MyClass(int a) : y(a) {}. Here y is a reference to a TEMPORARY variable, which disappears..


In your first constructor taking an int, you are referencing a temporary local variable.


I don't like your code.

The other answers pointed out why you are getting garbage value.

A better version of your code would look like this :

#include <iostream>
class MyClass
{

  int x;
  std::string c; //use std::string instead of char*
  int &y;

  public :

  MyClass (int a, std::string b): x(a), c(b),y(x) {}
  MyClass (const MyClass& myclass) : x (myclass.x), c(myclass.c), y(myclass.y) {}

  void print()
  {
     std::cout << x << " " << c << " " << y <<std::endl;
  }
};

int main()
{

    MyClass m1 (10, "Gaurav");
    MyClass m2 = m1;

    m1.print();
    m2.print();
}

Output :

10 Gaurav 10
10 Gaurav 10


In your code, step of confusion is line: m1.y = m1.x;

It looks like y gets assigned with value x, but that's not happening here. You are actually trying to change the value of a variable which y refers to. In your code that referred variable is a local temporary variable, which does not exist after its scope is over. That is why you are getting garbage value once the control goes to copy ctor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号