Guys, I'm experimenting with constructors and destructors and have tested the copy assignment constructor and fount that it also causes a copy constructor and hence a copy destructor.
Example foo ("test string"); // constructor overload
Example bar; // ordinary constructor called
bar = foo; // object already initialized: copy assignment called
/* A copy constructor and hence destructor called */
Example bar_force; // ordinary constructor called
// costructors.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> using namespace std; class Example { string* ptr; public: // constructors: Example() : ptr(new string) { cout << "in constructor\n"; } Example(const string& str) : ptr(new string(str)) { cout << "in constructor overload\n"; } // destructor: ~Example() { delete ptr; cout << "in distructor\n"; } // copy constructor: Example(const Example& x) : ptr(new string(x.content())) { cout << "in copy constructor\n"; } // copy assignment: Example operator= (const Example&) { cout << "in copy assignment\n"; return *this; } // move constructor: Example(Example&&) { cout << "in move constructor\n"; } // move assignment Example& operator= (Example&&) { cout << "in move assignment\n"; } // access content: const string& content() const { return *ptr; } }; void test_bed(void) { Example foo ("test string"); Example bar; // object initialization: copy constructor called bar = foo; // object already initialized: copy assignment called Example bar_force; //cout << "bar's content: " << bar.content() << '\n'; } int main() { test_bed(); while (1); return 0; }
So, why is it calling the copy constructor?