开发者

Copy constructor problem

I tried to use copy constructor using statement:

X y = X();

But copy constructor is not being called. I am using g++ 4.1.0. I set both X(const X&) and X(x&) constructor in the class.

Is this supposed to work or I am doing some very basic problem in the code?

My code for the class is

class A
{
 public:
  开发者_StackOverflow社区int i;

  A(int ii)
  {
   i = ii;
  }

  A(const A&)
  {
   i = 5;
  }

  A(A&)
  {
   i = -1;
  }

  A()
  {
   i = 5000;
  }
};

When I use it using A a = A(); or A a = A(100);, it does not work but when i use it A a(b); or A a = b; it works fine.

What is the point I am missing? I saw that according to wikipedia , it should work but it's not working in my case :(.

Thanks in advance for all your answers and comments.


The compiler is permitted to elide the call to the copy constructor in certain situations. Initializing an object from a temporary is one of them. In this case, the temporary is simply constructed in-place instead of constructing a temporary and then copying it into the named object.

You can call the copy constructor by constructing a named object then making a copy of that:

X x;
X y = x;


X y = X();

calls the default constructor. The copy constructor is the one that takes a reference to an instance you want copied.

The point of a copy constructor is to take another object of the same type, and make a copy of it. Everything else is not a copy constructor.


The copy constructor is called by the statements X x(y); or X x = y;.

When you call X x = X();, the default constructor is called.

When you call X x = X(100);, a constructor with one parameter is called. These are not copy constructors.


Copy constructors are called when you initialize an object with an another object:). In your first example it is totally natural that the copy ctors are not called, only constructors with the suitable parameter lists will be called.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜