Dynamic allocating of const member structures

Posted by Willy on Stack Overflow See other posts from Stack Overflow or by Willy
Published on 2010-05-08T10:26:02Z Indexed on 2010/05/08 10:28 UTC
Read the original article Hit count: 170

Filed under:

I've got class which is using plain-only-data struct with const variables and I'm not sure, if I'm allocating these structures in a proper way. It looks more or less like:

#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;

struct some_const_struct {
     const int arg1;
     const int arg2;
};

class which_is_using_above_struct {
 public:

  some_const_struct* m_member;

  const some_const_struct* const m_const_member;

 public:

  const some_const_struct& get_member() const { return *m_member; }

  const some_const_struct& get_const_member() const { return *m_const_member; }

  void set_member(const int a, const int b) {
   if(m_member != NULL) {
    delete m_member;
    m_member = NULL;
   }
   m_member = new some_const_struct((some_const_struct){a, b});
  }

  explicit which_is_using_above_struct(const int a, const int b)
   : m_const_member(new some_const_struct((const some_const_struct){a, b})) {
   m_member = NULL;
  }

  ~which_is_using_above_struct() {
   if(m_member != NULL) {
    delete m_member;
   }
   if(m_const_member != NULL) {
    delete m_const_member;
   }
  }

};

int main() {
 which_is_using_above_struct c(1, 2);
 c.set_member(3, 4);
 cout << "m_member.arg1 = " << c.get_member().arg1 << endl;
 cout << "m_member.arg2 = " << c.get_member().arg2 << endl;
 cout << "m_const_member.arg1 = " << c.get_const_member().arg1 << endl;
 cout << "m_const_member.arg2 = " << c.get_const_member().arg2 << endl;
 return 0;
}

I'm just not quite sure if the statement:

m_member = new some_const_struct((some_const_struct){a, b});

doesn't produce unnessesary use of some_const_struct's copy constructor, ergo allocating that struct twice. What do you think? And is it reasonable to make that struct's members const? (they're not supposed to change in their lifetime at all)

© Stack Overflow or respective owner

Related posts about c++