#include <stdio.h>
#include <memory>
struct A {
A() { printf("A()\n"); }
virtual ~A() { printf("~A()\n"); }
};
struct B : public A {
B() { printf("B()\n"); }
virtual ~B() { printf("~B()\n"); }
};
A&& foo() {
B b;
return std::move(b);
}
int main() {
A&& a = foo();
// const A& a = foo(); // same output
printf("checkpoint\n");
}
output:
A()
B()
~B()
~A()
checkpoint
checkpoint is the last line, why? I want foo to return reference instead of pointer to achieve polymorphism, is there a way to do it?
PS: this question may be related: Why a & b have the same address?
And what's more, I simply what a scheme that return an object created within the function, but not using pointers. For one reason pointers need delete, For another reason, think A & B are iterators that support range-based for loop, whose de-referencing operator* is redefined, using pointers or unique_ptr/shared_ptr is not a good idea, i guess.