Smart Pointer (auto_ptr) behavior
-
09-06-2021 - |
题
Not sure if someone has already asked this, but I see a strange behavior here:
I've declared two classes, one base and one derived with just one virtual method display()
.
class A {
public:
virtual void display() {
cout << "base class" << endl;
}
};
class B:public A {
public:
void display() {
cout << "derived class" << endl;
}
};
Now, in main()
, if I try to declare an auto_ptr
of A
and assign it a new instance of B
,
int main() {
auto_ptr<A> *a = (auto_ptr<A>*)new B();
a->display();
}
I get this error on compiling:
"
'class std::auto_ptr<A>'
has no member named 'display'"
Am I doing something wrong? Can someone explain the behavior?
解决方案
You are creating a pointer to an auto_ptr
. An auto_ptr
is an object that works like a pointer, so you don't need to add a *
.
You probably want:
auto_ptr<A> a(new B());
a->display();
Although I must recomment either Boost's smart pointers (scoped_ptr
and shared_ptr
) or C++11's std::unique_ptr
and std::shared_ptr
.
其他提示
auto_ptr<A> *a = (auto_ptr<A>*)new B();
That is doing something very strange. If you want to create an object and use a smart pointer to manage it, then initialise the smart pointer with a pointer to the object:
auto_ptr<A> a(new B);
a->display();
Why did you write auto_ptr<A> *a
? It should not be like that. Therefore you are getting this error. It should be auto_ptr<A> a(new B);
. Read here how it works.