问题
Say, the code
class Derived: public Base {....}
Base* b_ptr = new( malloc(sizeof(Derived)) ) Base(1);
b_ptr->f(2);
Derived* d_ptr = new(b_ptr) Derived(3);
b_ptr->g(4);
d_ptr->f(5);
seems to be reasonable and LSP is satisfied.
I suspect that this code is standard-allowed when Base and Derived are POD, and disallowed otherwise (because vtbl ptr is overwritten). The first part of my question is: please point out precise precondition of such an overwrite.
There may exist other standard-allowed ways to write over.
The second part of my question is: is there any other ways? What are their precise preconditions?
UPDATE: I do NOT want to write code like this; I am interested in theoretical possiblity (or impossibiliy) of such a code. So, this is "standard nazi" question, not a question "how can I ...". (Has my question to be moved to other stackoverflow site?)
UPDATE2&4: What about destructors? Supposed semantics of this code is "Base instance is (destructively) updated by slice of Derived instance". Let us assume, for the sake of simplicity, that Base class has a trivial destructor.
UPDATE3: The most intersting for me is the validity of access via b_ptr->g(4)
回答1:
You really need to do b_ptr = d_ptr
after placement-new of Derived
, in case the Base
subobject isn't first in the layout of Derived
. As written, b_ptr->g(4)
evokes undefined behavior.
The rule (3.8 basic.life
):
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:
- the storage for the new object exactly overlays the storage location which the original object occupied, and
- the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
- the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
- the original object was a most derived object (1.8) of type
T
and the new object is a most derived object of typeT
(that is, they are not base class subobjects).
You also should probably be destroying the old object before reusing its memory, but the standard doesn't mandate this. However failure to do so will leak any resources owned by the old object. The full rule is given in section 3.8 (basic.life
) of the Standard:
A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.
回答2:
You are initializing the same piece of memory twice. That won't end well.
Suppose for example that the Base
constructor allocates some memory and stores it in a pointer. The second time through the constructor, the first pointer will be overwritten and the memory leaked.
回答3:
I think the overwrite is allowed.
If it was me I'd probably call Base::~Base
before reusing the storage, so that the lifetime of the original object ended cleanly. But the standard explicitly allows you to reuse the storage without calling the destructor.
I don't believe your access via b_ptr is valid. The lifetime of the Base object has ended.
(See 3.8/4 in either standard for the rules on lifetime.)
And I'm also not entirely convinced that b_ptr must give the same address as was originally returned by the malloc() call.
回答4:
If you write this code more cleanly, it is easier to see what goes wrong:
void * addr = std::malloc(LARGE_NUMBER);
Base * b = new (addr) Base;
b->foo(); // no problem
Derived * d = new (addr) Derived;
d->bar(); // also fine (#1)
b->foo(); // Error! b no longer points to a Base!
static_cast<Base*>(d)->foo(); // OK
b = d; b->foo(); // also OK
The problem is that at the line marked (#1), b
and d
point to entirely separate, unrelated things, and since you overwrote the memory of the erstwhile object *b
, b
is in fact no longer valid at all.
You may have some misguided thoughts about Base*
and Derived*
being convertible pointer types, but that has nothing to do with the present situation, and for the sake of this example, the two types may as well be entirely unrelated. It is only one the very last two lines that we use the fact that the Derived*
is convertible to a Base*
, when we perform the actual conversion. But note that this conversion is a genuine value conversion, and d
is not the same pointer as static_cast<Base*>(d)
(at least as far as the language is concerned).
Finally, let's clean up this mess:
d->~Derived();
std::free(addr);
The opportunity to destroy the original *b
has passed, so we may have leaked that.
来源:https://stackoverflow.com/questions/9117358/is-it-allowed-to-write-an-instance-of-derived-over-an-instance-of-base