Re: Object Management
James Kanze wrote:
It depends. If the class has value semantics, and the address
of the object is part of it's value, then references won't work.
I find that I have a lot of smaller, helper classes whose
constructor takes a reference (since I don't allow null), but
which store the address as a pointer, since it must be changed
in the assignment operator.
Agreed, hence my mentioning there are many factors that
contribute. I've even contemplated this idea:
struct requires_assignment
{
requires_assignment(): ref_( value_ ){ };
private:
static const int value_;
const int& ref_;
};
const int requires_assignment::value_( 0 );
struct Derived : requires_assignment{
//Derived& operator=( const Derived& )
//{ return *this; }
};
int main()
{
Derived d1, d2;
d1 = d2; //Remove to compile, or
// define op=
return 0;
}
I have no use for it at this moment though.
All said, I find that I'm beginning to store references less
often, and have started using weak pointers or shared
pointers (it seems safer). I only store a reference when
I'm really sure. For instance if a nested class requires
a reference to its parent, and the parent is the owner
(given the nested does not require value semantics,
yes, which in my case I've found to be rare). Admittedly
I've not had the time to look into GC yet (from other posts
I gather you would consider this incompetent), and I know
that in some cases knowing when the lifetime of something
ends is Grey, for example:
I (or we) often use the Command pattern to communicate
between threads, usually wrapping member functions, and
in that case one wants the reference (or pointer to receiver)
to outlast the call, or one wants to at least see when the
receiver dies. Shared pointers are an option, but I don't trust
them entirely due to the fact that for this scenario simultaneous
read/writes are required to the shared pointer. OTOH
encapsulating calling into objects from other threads in this
way (using commands) are very beneficial to us because
it reduces data sharing (apart from the encapsulated pointer
to receiver) and allows for objects to be bound to threads,
promoting a kind of concurrent sequential style of
programming.
Regards,
Werner