problems with dynamic_cast
I have this snippet of the code:
void addLineRelative(LineNumber number, LineNumber relativeNumber) {
list<shared_ptr<Line> >::iterator i;
findLine(i, number);
if(i == listOfLines.end()){
throw "LineDoesNotExist";
开发者_如何学Go }
line 15 if(dynamic_cast<shared_ptr<FamilyLine> >(*i)){
cout << "Family Line";
} else {
throw "Not A Family Line";
}
}
I have class Line and derived from it FamilyLine and RegularLine, so I want find FamilyLine
my program fails on the line 15, I receive an error
cannot dynamic_cast target is not pointer or reference
can somebody please help, thanks in advance
edited
I tried this one:
shared_ptr<FamilyLine> ptr(dynamic_cast<shared_ptr<FamilyLine> >(*i));
if(ptr){
//do stuff
}
the same error
edited
void addLineRelative(LineNumber number, LineNumber relativeNumber) {
list<shared_ptr<Line> >::iterator i;
findLine(i, number);
if(i == listOfLines.end()){
throw "LineDoesNotExist";
}
shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr){
cout << "Family Line";
} else {
throw "Not A Family Line";
}
}
receive this error
Multiple markers at this line
- `dynamic_pointer_cast' was not declared in this
scope
- unused variable 'dynamic_pointer_cast'
- expected primary-expression before '>' token
shared_ptr
does not implicitly convert to a pointer - it is a class-type object - and dynamic_cast
, static_cast
and const_cast
all operate on pointers only.
While you could use dynamic_cast
on shared_ptr<T>::get()
, its better to use dynamic_pointer_cast<FamilyLine>()
instead as you might otherwise accidentally introduce double-delete
s:
Returns:
* Whendynamic_cast<T*>(r.get())
returns a nonzero value, ashared_ptr<T>
object that stores a copy of it and shares ownership with r;
* Otherwise, an emptyshared_ptr<T>
object.
[...]
Notes: the seemingly equivalent expression
shared_ptr<T>(dynamic_cast<T*>(r.get()))
will eventually result in undefined behavior, attempting to delete the same object twice.
E.g.:
shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr) {
// ... do stuff with ptr
}
精彩评论