Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a static member function on non-existing object

Something like this just came up in another question and piqued my interest. Given that Foo is declared like this:

struct Foo
{
     static void bar() {std::cout << "Bar!";}
};

doing something like this seems to work just fine:

std::vector<Foo> v;
v[10].bar();

However, is this usage actually legal? What if bar() weren't declared static?

like image 210
Knoep Avatar asked Dec 24 '22 13:12

Knoep


2 Answers

doing something like this seems to work just fine:

That doesn't mean it's OK.

Please read http://c-faq.com/ansi/experiment.html which has a great analogy from Roger Miller:

"Somebody told me that in basketball you can't hold the ball and run. I got a basketball and tried it and it worked just fine. He obviously didn't understand basketball."

Accessing v[10] is undefined behaviour. It doesn't matter if you call a member function on it, even just accessing v[10] is undefined. (And as pointed out in the comment, the object expression is evaluated even when calling a static member function, which IMHO should be obvious, because v[10] is not used in an unevaluated context like sizeof(v[10]) or decltype(v[10])).

You cannot write C++ code with the view "this seems to work just fine" and assume that means the program is correct.

like image 82
Jonathan Wakely Avatar answered Jan 18 '23 22:01

Jonathan Wakely


According to [class.static]/1 (emphasis mine):

A static member s of class X may be referred to using the qualified-id expression X​::​s; it is not necessary to use the class member access syntax to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object expression is evaluated.

v[10] must be evaluated, bar being static or not is immaterial. The vector will be accessed out of bounds for sure, so it's definitely undefined behavior.

like image 25
StoryTeller - Unslander Monica Avatar answered Jan 18 '23 22:01

StoryTeller - Unslander Monica