small design issues with creating views (portions) of a class

E

er

hi,

here's a piece of code and questions below. any suggestion would be
appreciated.

class Write_view{
public:
Write_view(Obj&,unsigned int index){/*.../*};
void fun(...){/*...*/};//writes in portion index of Obj
};

class Obj{
public:
Write_view view(unsigned int index){
return Write_view(*this,index)
};
friend class Write_view;

private:
//some data
};

a) should i be worried that Obj may be deleted before Write_view?
perhaps i could make the constructor of Obj private and use a friend
helper function to call the constructor and return a shared_ptr<Obj>.
is that an overkill or it sounds fine?

b) i'm unhappy with view(index) returning an object because i only
need the same object no matter how often i call it on the same object.
how about this?

shared_ptr<Write_view> view(unsigned int index){
if(count[index]==0){
views[index]=shared_ptr<Write_view>(new
Write_view(*this,index));
};
return views[index];// map<unsigned int, shared_ptr<Write_view> >
views
};

or this?

Write_view& view(unsigned int index){
return *shared_ptr<Write_view>(new Write_view(*this,index));
};

c) is there a better way altogether?
 
E

er

hi,

here's a piece of code and questions below. any suggestion would be
appreciated.

class Write_view{
public:
Write_view(Obj&,unsigned int index){/*.../*};
void fun(...){/*...*/};//writes in portion index of Obj

};

class Obj{
public:
Write_view view(unsigned int index){
return Write_view(*this,index)
};
friend class Write_view;

private:
//some data

};

a) should i be worried that Obj may be deleted before Write_view?
perhaps i could make the constructor of Obj private and use a friend
helper function to call the constructor and return a shared_ptr<Obj>.
is that an overkill or it sounds fine?

b) i'm unhappy with view(index) returning an object because i only
need the same object no matter how often i call it on the same object.
how about this?

shared_ptr<Write_view> view(unsigned int index){
if(count[index]==0){
views[index]=shared_ptr<Write_view>(new
Write_view(*this,index));
};
return views[index];// map<unsigned int, shared_ptr<Write_view> >
views
};

or this?

Write_view& view(unsigned int index){
return *shared_ptr<Write_view>(new Write_view(*this,index));
};

c) is there a better way altogether?

well actually i found out that this approach is convoluted. what i do
now instead is write an impl class that does all the operations and
has operator[] return a class with a limited interface that forwards
to ptr<impl>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top