Does the nonvirtual member function on an unadjusted “object” call a well-defined one?

Inside the constructor, non-virtual member functions are allowed.

From this fact it follows that the following code fragment is clearly defined?

struct A { void foo { std::cout << "Hi there! My address is: " << this; } }; A * a = nullptr; a->foo (); 

Answer

With the help of some links provided in the comments and links provided on related pages, now I think that the answer can be found, for example. in

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3035.pdf

§3.8 par. 5, p. 66:

"Before the life object started, but after the storage that will occupy the object was allocated ... [t] it has undefined behavior if [...] the pointer is used to access a non-stationary data element or calls non-stationary member function of the object "

Then there should be even more undefined to call the member function, if the storage was not allocated at all.

I assume that one important reason why it is a good idea to make it undefined is explained here: https://stackoverflow.com/a/416829/

+6
source share
1 answer

This code has undefined behavior.

Note that inside the constructor, you can also call the virtual member function.

A somewhat complicated part is the invocation of a virtual member function during element initialization before the constructor code begins. It’s still valid, but it’s not obvious what is happening (the fact is that until the constructor code starts the object, the object is still not considered an instance of its class, and the virtual member functions are sent to the base class).

Some compilers give a warning if you use this in a member's initialization list precisely because the this pointer will behave strangely at this point (it will start to behave normally only after the constructor starts).

The code obviously works because most compilers use the VMT approach to dispatch methods, but VMT is not required to invoke a non-virtual method, and thus, if the method code does not play this out in any way, then it seems to work. However, the fact that the code seems to work in the implementation (or even in any implementation, for that matter) still does not make it legal C ++ code.

+4
source

All Articles