简体   繁体   中英

Simple Java code, having trouble creating a C++ equivalent (private static members and public accessor methods)

I'm a Java developer with 7 years of experience but I'm almost entirely new to C++. This isn't homework or even for real paid work. I'm just delving into C++ and having trouble emulating this one particular pattern that I use frequently in Java.

Basically (in Java):

    public class ExampleManager
    { 
       private static Example _example;

       public static Example getExample()
       { 
          return _example;
       }

       public static void setExample(Example example)
       {
          _example = example;
       }
    } 

I've so far tried about four variants with what I've learned about C++. I found that passing 'example' with the same syntax gets me a copy of 'example' stored in the class. I understand most of the logic behind pointers, just not a lot of the specifics. This example would go a long way to help me with that.

If someone could give me equivalent C++ code to this so that I can break it down line by line and step through it, I would appreciate it very much.

I don't use this pattern as is in Java, but its the bones of the pattern I use to maintain thread safe access to single instance members.

The basically equivalent code in C++ would be this:

class ExampleManager
{ 
private:
   static std::shared_ptr<Example> _example;

public:
   static std::shared_ptr<Example> getExample()
   { 
      return _example;
   }

   static void setExample(std::shared_ptr<Example> example)
   {
      _example = example;
   }
};

It makes use of the std::shared_ptr class, which does most of the memory handling stuff for you (you only have to new objects, basically just like in Java).

We do not use "raw" pointers (ie Example * ) here; usage of "raw" pointers is usually frowned upon (unless you're working in an environment with limited resoures, or close to hardware), since it gains you little in terms of performance but can lead to ugly problems (memory leaks, double deletions, ...) if not considered carefully.

Please note that the shared_ptr used above is only part of the standard since C++11. Most halfway recent compilers will already accept its usage like shown above; for some a bit older ones you might have to do special things:

  • eg for g++ <= 4.6, add -std=c++0x to compilation command line
  • for some you might have to use std::tr1::shared_ptr
  • if both of the above options fail, you can use boost::shared_ptr from the boost libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM