Skip to content

Instantly share code, notes, and snippets.

@d
Created May 21, 2019 22:01
Show Gist options
  • Save d/227036a8c0c660da4023c24b2abe2593 to your computer and use it in GitHub Desktop.
Save d/227036a8c0c660da4023c24b2abe2593 to your computer and use it in GitHub Desktop.
object life time

Object life time: the implicit contract between functions and objects

An example of non-owning pointers

What expectations does F have about its parameter E?

void F(CExpression *E) {
  do_something_with_E(...);
  ...
  E->foo();
}

If E != nullptr, then E should point to a valid CExpression object **throughout the execution of F

Is this trivial? No

static CExpression *GV = ...;

void do_something_with_E(CExpression *E) {
  stuff(E);
  GV->Release();
  GV = ExpressionFactory(...);
  bar();
}

function F doesn't own parameter E

Example of owning pointers

struct CGroupExpression : CRefCount<CGroupExpression> {
  COperator *pop_;
  CGroupExpression(COperator *pop) : pop_(pop) {}
  ~CGroupExpression() {
  	pop_->Release();
  }
}

CGroupExpression *G(COperator *O) {
  pop->AddRef();
  CGroupExpression *GE = GPOS_NEW(mp) CGroupExpression(pop);
  return GE;
}
template <class T, class = std::enable_if_t<std::is_pointer<T>::value>>
using owner = T;

owner<CGroupExpression*> G(COperator *O) {
  pop->AddRef();
  owner<CGroupExpression*> GE = GPOS_NEW(mp) CGroupExpression(pop);
  return GE;
}

Where do we call Release()

  • locally created and then destroyed pair GPOS_NEW() / Release()

    libgpopt/include/gpopt/base/CStateMachine.h:491 CStateMachine::OsDiagramToGraphviz

  • In destructors libgpdbcost/src/CCostModelGPDB.cpp:161 CCostModelGPDB::~CCostModelGPDB

  • local variables, returned from a ownership-returning function libgpopt/include/gpopt/base/CUtils.h:1294 CUtils::PexprLogicalCorrelatedQuantifiedApply

    libgpopt/include/gpopt/xforms/CXformApply2Join.h:202 CXformApply2Join::Decorrelate

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