It would seem more sensible to me to have
the data member of the Node class, to be
a pointer to "some type". Thoughts?
I don't think I've ever seen such a case, care to post an example?
> It would seem more sensible to me to have
> the data member of the Node class, to be
> a pointer to "some type". Thoughts?
That's why most do!
--
Ian Collins
Well, then you just have to worry about even more memory management as
you allocated the sub-field. I don't understand the part about the
default constructor. Why do you need to default construct them?
Can't you pass the information to the Node when you create?
Node n = new Node(43);
Node(int value) : m_value(value){} // Nt default constructed, but
"value" is unique.
Joe Cook
#include <list>
struct foo
{
foo( char )
{ }
foo( foo const& )
{ }
};
int main( void )
{
std::list< foo >
foos( 3, foo( 'a' ) ); // fine, copy constructor used
foos.push_back( foo( 'b' ) ); // fine, copy constructor used
foos.resize( 10 ); // error, no match for foo::foo( )
return 0;
}
Not really. std::list just requires that the contained element be copy
constructable, not default constructable. Big difference. (The
forthcoming C++0x standard changes the requirement into move
constructable, which is even better.)
> It would seem more sensible to me to have
> the data member of the Node class, to be
> a pointer to "some type". Thoughts?
Then define it like that:
std::list<your_type *>
instead of
std::list<your_type>
This is fine, unless you also want std::list to have ownership
semantics over the contained pointed-to objects, in which case, yes,
std::list does not do that. This is a real use case which I
occasionally hit. You're welcome to roll your own on top of std::list.
It's a ~20-30 line exercise left to the reader.
Are you talking about your (maybe hypothetical) own linked list
implementation, or are you talking about std::list?
If you are making your own linked list implementation, then there are
two possibilities:
1) In the constructor of the Node structure, call the data member
constructor (or copy constructor) is called appropriately.
2) If this is not feasible for some reason, then you'll have to resort
to lower-level trickery: Rather than instantiate objects of type Node,
only reserve space for them (using eg. std::allocator or ::new) and then
use placement-new to construct the data member with the proper
constructor parameters.
Do they? Mine never did, and the implementations of std::list
that I've seen don't either.
But I don't see the reason behind the original posters comments.
Why would a Node type which contains the data type require a
default constructor for the data type?
--
James Kanze
You're right, I was answering with my C programmers hat on! I really
should find better things to do on a Sunday afternoon...
--
Ian Collins