c++ - Dynamically allocated object producer -


look @ class:

//hpp class {   public:     a();     ~a();     b *fetchnew();    private:     b *currentvalue; }   //cpp a::a() {}  a::~a {    delete currentvalue; }  b *a::fetchnew() {     delete currentvalue;     currentvalue = new b();     //apply magic currentvalue     return currentvalue; } 

this class holds pointer instance of class b. every time fetchnew() called, old 1 gets deleted, new 1 allocated , magic applied it, after new , shiny currentvalue returned.

this method called (in real life, it's method returns view matrix in game's main loop, it's called once every frame, 60 times second).

once object gets deleted, deletes current currentvalue, otherwise leak.

is there prettier way achieve this?

edit:

here's actual code, since has twist (just fetchnow() method):

glm::mat4x4 *camera::getviewmatrix() {     //transformation <<-apply shiny , fancy magic;      delete viewmatrix;     viewmatrix = new glm::mat4x4();     *viewmatrix *= glm::mat4_cast(transformation->getrotation());     *viewmatrix = glm::translate(*viewmatrix, transformation->getposition());      return viewmatrix; } 

is there prettier way achieve this?

i recommend rather use std::unique_ptr<b> raw pointer b*:

//hpp #include <memory> class {   public:     a();     ~a();     std::unique_pty<b> fetchnew();    private:     // don't need that: b *currentvalue; } 

//cpp a::a() {}  a::~a {    // don't need that: delete currentvalue; }  std::unique_ptr<b> a::fetchnew() {     // don't need that: delete currentvalue;     std::unique_ptr<b> newvalue = std::make_unique<b>();     // apply magic newvalue , dereference using * or -> raw pointer     return newvalue; } 

this approach has several advantages:

  • you don't have care deletion or memory leaks in a
  • the transfer of ownership result of fetchnew() semantically clear
  • it's more clear api, client know ownership of pointer , not have riddle if need delete instance or not
  • you give client flexibility determine lifetime scope of b instance themselves.

as edited addition should like:

std::unique_ptr<glm::mat4x4> camera::getviewmatrix() {     //transformation <<-apply shiny , fancy magic;      std::unique_ptr<glm::mat4x4> viewmatrix = std::make_unique<glm::mat4x4>();     *viewmatrix *= glm::mat4_cast(transformation->getrotation());     *viewmatrix = glm::translate(*viewmatrix, transformation->getposition());      return viewmatrix; } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -