new object in c++
i'm new to c++ programming and i will be happy if you can help me. i tried to write this code:
bool RailwayLineList:: AddInTail(const RailwayLine& data)
{
//there is no linked list to add the element
if(this==NULL)
return false;
RailwayLineLink 开发者_Go百科*newLink = new RailwayLineLink(data);
}
when i tried to debug it i saw that the copy constructor had been called and the data had been initialized with some garbage (the class is using a default constructor).
why is the copy constructor being called?
A copy constructor is a constructor with a specific signature. It takes a single parameter, of const reference to the same type being constructed. So for a class Foo
, the copy constructor looks like this:
Foo::Foo(const Foo&)
There are 2 other kinds of constructors: default and convert. The default constructor takes no parameters (or can be called as if it took no parameters, eg, all parameters have defaults):
Foo::Foo()
...and the convert destructor is basically anything else. For example:
Foo::Foo(const Bar&)
why is the copy constructor being called?
In your case, you're calling a RailwayLineLink
constructor but passing in a const reference to a RailwayLine
, so you're actually calling a convert constructor, not a copy constructor.
The convert constructor is called because you called it:
new RailwayLineLink(data);
This constructs a new RailwayLineLink
object, passing data
as the one and only parameter to the constructor.
If you have an empty convert constructor, that looks something like this:
RailwayLineLink::RailwayLineLink(const RailwayLine&)
{
}
...then all of the members of the new copy will be default constructed, and probably contain garbage.
Typically when you implement a copy constructor, you would want to do some kind of memberwise copy from the original to the copy, like this:
RailwayLineLink::RailwayLineLink(const RailwayLine& rhs)
: value_(rhs.value_)
{
}
if (this == NULL)
is technically a valid construct but by the time it's reached, undefined behavior has been generated already if the statement could be true. DO NOT DO THIS!!!
精彩评论