0

I have tried my code to find how copy constructor works. This is my code:

#include <iostream>

using namespace std;

class B{
public:
    B(){
        cout << "B()\n";
    }
    B(const B& b){
        cout << "B(const B&)\n";
    }
    ~B(){
        cout << "~B()\n";
    }
};

int main(){
    B b = B();

    return 0;
}

For the code B b = B(), I think the process is like this:

  1. Call constructor B(), print B(), return a temporary object of type B;
  2. Call the copy constructor B(const B&), pass the returned object in step 1 as arguments, print B(const B&), initialize variable b.

But my code just outputs B(), which means no copy constructor is called. What is the problem?

Zachary
  • 1,633
  • 2
  • 22
  • 34
  • 4
    The key phrase you're looking for to answer this question is "[copy elision](http://en.wikipedia.org/wiki/Copy_elision)". – In silico Jun 24 '13 at 03:37
  • @Insilico But I disable the **optimization** option of my **VC++ Compiler**. – Zachary Jun 24 '13 at 09:23

0 Answers0