Calling a static member function on a nonexistent object

Something like this just arose in another question and aroused my interest. Given that it is Foodeclared as follows:

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

doing something like this seems to be fine:

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

However, is this use legal? What if bar()were not announced static?

+4
source share
2 answers

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

X X:: s; . , .

v[10] , bar , . , undefined.

+4

- , , :

, .

http://c-faq.com/ansi/experiment.html, :

"- , , , . , ".

v[10] - undefined. , -, v[10] undefined. ( , -, , v[10] , sizeof(v[10]) decltype(v[10])).

++ ", , ", , .

+9

Source: https://habr.com/ru/post/1688135/


All Articles