I understand that calling a method (which accesses any of the class members) from a deleted object is undefined behavior but I am wondering if same is true for the method which does not access any of the class members.
Asked
Active
Viewed 43 times
-1
-
8Dereferencing an invalid pointer in any way is *undefined behavior*, there is no special clause regarding accessing members – UnholySheep Mar 22 '19 at 17:51
-
Undefined behavior. This means even you can access members if they are not deleted. But this depends on implementation libc++ – Muhammet Ali Asan Mar 22 '19 at 17:54
-
2The actual failure mode can vary from "it appears to work, at least for now" to instant death, depending on the compiler, type of method and other things, but it's always UB. – Useless Mar 22 '19 at 17:55
-
1I disagree that this is a duplicate. IMO, that question is about calling a function on a non-existent object, whereas this question is about calling a function on an object out-of-lifetime. It's UB either way. – Justin Mar 22 '19 at 17:59
-
1@Justin I disagree with you, the duplicate has sufficient information. Invoking a function via a dangling pointer vs. doing with a `nullpointer` doesn't make any real difference. – πάντα ῥεῖ Mar 22 '19 at 18:29
-
@πάνταῥεῖ I disagree. Yes, the outcome is the same, but it exercises a different area of the standard. You don't even need a pointer to have a "deleted object" e.g. by calling the object's destructor. – Justin Mar 22 '19 at 18:30
-
@Justin _undefined behavior_ is _**undefined**_, so what? – πάντα ῥεῖ Mar 22 '19 at 18:32
1 Answers
2
It is undefined behavior to call a non-static member function on an object which is not alive (source, or [basic.life] in the standard).
Given:
struct MyType {
int answer() const {
return 42;
}
};
If you have a dead MyType foo
, foo.answer()
is undefined behavior.

Justin
- 24,288
- 12
- 92
- 142