Given a pointer to a C++ object, what is the preferred way to call a static member function?

前端 未结 7 1860
挽巷
挽巷 2020-12-21 04:56

Say I have:

class A {
public:
    static void DoStuff();

    // ... more methods here ...
};

And later on I have a function that wants to

相关标签:
7条回答
  • 2020-12-21 05:28

    Jon Skeet opened my eyes to why you should not call a static method through an instance pointer. His example is in Java, but the concept applies to C++, too:

    Thread t = new Thread(...);
    t.start();
    t.sleep(1000); // Which thread does it look like this will affect?
    

    As I commented when I first read his answer: "Until I read [Jon's post], I considered being able to call static methods through an instance reference a feature. Now I know better."

    In short, call static methods using the class name, not an instance. In my opinion, it's more than a style issue - it can result in misleading, buggy code.

    0 讨论(0)
提交回复
热议问题