push_back

Started by
6 comments, last by snk_kid 18 years, 8 months ago
Hello everyone, My class uses pointers and I'd like to add instances of it to a std::vector using push_back(). I've overloaded my class's equals (=) operator, but it now seems push_back doesn't use it. How can I ensure the vector's push_back method handles my class properly? Kind regards, Graham
Advertisement
Assuming you're trying to hold a vector of pointers (if I've read you right)...

class YourClass;std::vector< YourClass *> vec;YourClass *x = new YourClass();vec.push_back( x );


Normally all you need for functioning of push_back is the definition of a
copy constructor.


class MyClass
{
MyClass( MyClass& mc )
{...}

}
He seems to be saying that his class uses pointers internally (as in, it's not a POD).

You need to know that operator= and the copy constructor are tied. More often than not, what is called by push_back is the copy constructor, and not the assignment operator.
Thanks evolutional et al., it is the Copy Constructor I was looking for and not the equals operator.

( The class had member vars that were pointers. )

Thanks,
Graham
Quote:Original post by Sparhawk42
Normally all you need for functioning of push_back is the definition of a
copy constructor.


class MyClass
{
MyClass( MyClass& mc )
{...}

}


That is not a copy constructor, a copy constructor takes a constant reference. If you do that then there still is a copy constructor implicitly defined to do the default member-wise copy.
Quote:Original post by snk_kid
That is not a copy constructor, a copy constructor takes a constant reference. If you do that then there still is a copy constructor implicitly defined to do the default member-wise copy.


Incorrect. A constructor for a class X that takes as an argument X & is a valid copy constructor. See section 12.1 paragraph 10 and section 12.8 paragraph 2 in the C++ standard.
Quote:Original post by SiCrane
Incorrect. A constructor for a class X that takes as an argument X & is a valid copy constructor. See section 12.1 paragraph 10 and section 12.8 paragraph 2 in the C++ standard.


Well its not a great idea to be doing in any case even though it is still a copy constructor, its good practice for copy constructors to take constant references. Constructors that take non constant references would be better for move semantics and move constructors if it ever gets standardized and/or supported by all C++ compilers.

This topic is closed to new replies.

Advertisement