Skip to content

Instantly share code, notes, and snippets.

@theidexisted
Created June 6, 2015 14:43
Show Gist options
  • Select an option

  • Save theidexisted/980df1c6265998f87980 to your computer and use it in GitHub Desktop.

Select an option

Save theidexisted/980df1c6265998f87980 to your computer and use it in GitHub Desktop.
#include <vector>
#include <iostream>
static int gCounter = 0;
class Foo {
public:
Foo(int n = 0)
:pval_(new int(n)) {
index_ = gCounter++;
}
~Foo() {
delete pval_;
std::cout << "dtor: " << index_ << std::endl;
}
private:
int* pval_{nullptr};
int index_{0};
};
int main() {
std::vector<Foo> vec(20);
std::vector<Foo> tmp(10);
vec = tmp;
std::cout << "copy done" << std::endl;
return 0;
}
/*
dtor: 10
dtor: 11
dtor: 12
dtor: 13
dtor: 14
dtor: 15
dtor: 16
dtor: 17
dtor: 18
dtor: 19
copy done
dtor: 20
dtor: 21
dtor: 22
dtor: 23
dtor: 24
dtor: 25
dtor: 26
dtor: 27
dtor: 28
dtor: 29
dtor: 20
dtor: 21
dtor: 22
dtor: 23
dtor: 24
dtor: 25
dtor: 26
dtor: 27
dtor: 28
dtor: 29
*/
@theidexisted

Copy link
Copy Markdown
Author
#include <vector>
#include <iostream>

static int gCounter = 0;
class Foo {
 public:
  Foo(int n = 0)
      :pval_(new int(n)) {
        index_ = gCounter++;
  }
  ~Foo() {
    delete pval_;
    std::cout << "dtor: " << index_ << std::endl;
  }
  Foo& operator=(const Foo& other) {
    std::cout << "operator= " << index_ << std::endl;
    int* tmp = new int(*other.pval_);
    delete pval_;
    pval_ = tmp;
  }
 private:
  int* pval_{nullptr};
  int index_{0};
};

int main() {
  std::vector<Foo> vec(20);
  std::vector<Foo> tmp(10);
  vec = tmp;
  std::cout << "copy done" << std::endl;
  return 0;
}
/*
operator= 0
operator= 1
operator= 2
operator= 3
operator= 4
operator= 5
operator= 6
operator= 7
operator= 8
operator= 9
dtor: 10
dtor: 11
dtor: 12
dtor: 13
dtor: 14
dtor: 15
dtor: 16
dtor: 17
dtor: 18
dtor: 19
copy done
dtor: 20
dtor: 21
dtor: 22
dtor: 23
dtor: 24
dtor: 25
dtor: 26
dtor: 27
dtor: 28
dtor: 29
dtor: 0
dtor: 1
dtor: 2
dtor: 3
dtor: 4
dtor: 5
dtor: 6
dtor: 7
dtor: 8
dtor: 9
 */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment