J
Jeff
After reading all I could find about auto_ptr, I decided to write a
little program to test my comprehension:
#include <iostream>
#include <memory>
class A {
public:
void say_hi() {
std::cout << "hi!" << std::endl;
}
void say_ih() {
std::cout << "!ih" << std::endl;
}
};
void f(std::auto_ptr<A> fs_pa) {
fs_pa->say_hi();
}
int main() {
std::auto_ptr<A> pa(new A);
pa->say_ih();
f(pa);
pa->say_ih();
}
This is what I expected would happen:
1. a new A is created, and its ownership is assumed by pa.
2. the say_ih() function is called with no problems
3. when f() is called, pa is copied into fs_pa, thereby transfering
ownership of the A object to fs_pa, and leaving pa with a null pointer
4. the A object's say_hi() function is called through fs_pa
5. fs_pa goes out of scope, and therefore runs its deconstructor,
which calls 'delete' on the chunk of memory which holds the A object
6. when we return to main(), pa now holds a null pointer, and
"pa->say_ih();" should cause a runtime error.
To my surprise, this piece of code produced no errors at either compile
time or at run time. Can anybody tell me what the problem is with my
reasoning?
little program to test my comprehension:
#include <iostream>
#include <memory>
class A {
public:
void say_hi() {
std::cout << "hi!" << std::endl;
}
void say_ih() {
std::cout << "!ih" << std::endl;
}
};
void f(std::auto_ptr<A> fs_pa) {
fs_pa->say_hi();
}
int main() {
std::auto_ptr<A> pa(new A);
pa->say_ih();
f(pa);
pa->say_ih();
}
This is what I expected would happen:
1. a new A is created, and its ownership is assumed by pa.
2. the say_ih() function is called with no problems
3. when f() is called, pa is copied into fs_pa, thereby transfering
ownership of the A object to fs_pa, and leaving pa with a null pointer
4. the A object's say_hi() function is called through fs_pa
5. fs_pa goes out of scope, and therefore runs its deconstructor,
which calls 'delete' on the chunk of memory which holds the A object
6. when we return to main(), pa now holds a null pointer, and
"pa->say_ih();" should cause a runtime error.
To my surprise, this piece of code produced no errors at either compile
time or at run time. Can anybody tell me what the problem is with my
reasoning?