Leigh Johnston wrote:
"Leigh Johnston" <leigh@i42.co.uk> wrote in message
news:GcqdnSD3UOs4HiHWnZ2dnUVZ8j2dnZ2d@giganews.com...
"Daniel T." <daniel_t@earthlink.net> wrote in message
news:daniel_t-548CC7.08435507042010@70-3-168-216.pools.spcsdns.net...
James Allsopp <jamesaallsopp@googlemail.com> wrote:
I have a list of item objects which I'm trying to find which of these
objects are close to each other. The data in these objects does not
change. I const::iterate though the vector these are stored in, and
where the condition is met, create a linker object in another class.
I
don't want to recreate the classes, just store a reference to them.
The code from the linker is
class linker{
public:
linker( const item &spectra, const item & core, double
distance):spectra(spectra),core(core),distance(distance){};
const item & spectra;
const item & core;
double distance;
int toString() const;
};
References were designed for argument passing, and it isn't
appropriate
to use them as member-variables. Hold your items in const pointers
instead.
Not true, references were designed to be an alias to another object not
just for argument passing. It is perfectly fine to have reference
member
variables but if the class needs to be Assignable (to be compatible
with
a container for example) then reference member variables may not be
suitable. Your generalization is simply wrong though.
/Leigh
It is possible to re-seat a member reference in a user provided
assignment
operator by doing something similar to the following:
const foo& foo::operator=( const foo& other)
{
if ( this != &other )
{
this->~foo(); // lifetime of *this ends
new (this) foo(other); // new object of type foo created
}
return *this;
}
Yes, it is possible. However, there are some traps with that idea of
which
one should be aware. E.g., that assignment operator does not really
interact
nicely with inheritance in OO design (virtual members and such). E.g.:
#include <iostream>
struct X {
X ( void ) {
std::cout << "creating X\n";
}
virtual
~ X ( void ) {
std::cout << "destroying X\n";
}
X & operator= ( X const & other ) {
if ( this != &other ) {
// this->~X();
this->X::~X();
new (this) X (other);
}
return ( *this );
}
};
struct Y : public X {
Y ( void ) {
std::cout << "creating Y\n";
}
~ Y ( void ) {
std::cout << "destroying Y\n";
}
Y & operator= ( Y const & other ) {
X::operator=( other );
return (*this );
}
};
int main ( void ) {
Y* a_ptr = new Y;
Y* b_ptr = new Y;
*a_ptr = *b_ptr;
delete a_ptr;
std::cout << "-----------\n";
Y* c_ptr = new Y;
delete c_ptr;
}
This has formally undefined behavior [3.8/7] and on my machine prints:
creating X
creating Y
creating X
creating Y
destroying X
destroying X
-----------
creating X
creating Y
destroying Y
destroying X
Best
Kai-Uwe Bux
are better than one.