0

Error case (why does the destructor of class A will be called by twice?):

class A {};
std::unique_ptr<A>&& get() {
  std::unique_ptr<A> p(new A());
  return std::move(p);
}
int main() {
  std::unique_ptr<A> k = get();
}

Got the below error when running the above code:

test(32033,0x116d375c0) malloc: *** error for object 0x7ffee5398818: pointer being freed was not allocated
test(32033,0x116d375c0) malloc: *** set a breakpoint in malloc_error_break to debug
[1]    32033 abort      ./test

Normal Case:

class A {};
std::unique_ptr<A> get() {
  std::unique_ptr<A> p(new A());
  return std::move(p);
}
int main() {
  std::unique_ptr<A> k = std::move(get());
}
Jason Yu
  • 1,886
  • 16
  • 26

0 Answers0