[ create a new paste ] login | about

Link: http://codepad.org/kAeUsq2i    [ raw code | output | fork ]

C++, pasted on Feb 17:
#include <iostream>
#include <vector>
#include <cstring>

using namespace std;
class A {
public:
  A();
  A(const char* _text);
  A(const A& a);
  A& operator=(const A& a);
  ~A();
  char* date()const;
private:
  char* text;
};

A::A() : text(0) {
  cout << "constructor ()" << endl;
}

A::A(const char* _text) {
  text = new char[strlen(_text) + 1];
  strcpy(text, _text);
  cout << "constructor (const char*)" << endl;
}

A::A(const A& a) {
  text = new char[strlen(a.text) + 1];
  strcpy(text, a.text);
}

A& A::operator=(const A& a) {
  if (this != &a) {
    if (text)
      delete[] text;
    text = new char[strlen(a.text) + 1];
    strcpy(text, a.text);
  }
  return *this;
}

A::~A() {
  cout << "destructor " << endl;
  if (text) {
    delete[] text;
    cout << "delete" << endl;
  } else {
    cout << "not delete" << endl;
  }
}

char* A::date() const {
  return text;
}

int main(){
  vector<A> vec;
  A b;
  
  vec.push_back("vec test"); // コピーコンストラクタが呼び出される
  cout << vec.at(0).date() << endl;
  A a("class A test");
  cout << a.date() << endl;

  b = a; // 代入演算子関数が呼び出される
  cout << b.date() << endl;
  
  return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
constructor ()
constructor (const char*)
destructor 
delete
vec test
constructor (const char*)
class A test
class A test
destructor 
delete
destructor 
delete
destructor 
delete


Create a new paste based on this one


Comments: