Search Results

Search found 45845 results on 1834 pages for 'static void main'.

Page 14/1834 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Why should main() be short?

    - by Stargazer712
    I've been programming for over 9 years, and according to the advice of my first programming teacher, I always keep my main() function extremely short. At first I had no idea why. I just obeyed without understanding, much to the delight of my professors. After gaining experience, I realized that if I designed my code correctly, having a short main() function just sortof happened. Writing modularized code and following the single responsibility principle allowed my code to be designed in "bunches", and main() served as nothing more than a catalyst to get the program running. Fast forward to a few weeks ago, I was looking at Python's souce code, and I found the main() function: /* Minimal main program -- everything is loaded from the library */ ... int main(int argc, char **argv) { ... return Py_Main(argc, argv); } Yay python. Short main() function == Good code. Programming teachers were right. Wanting to look deeper, I took a look at Py_Main. In its entirety, it is defined as follows: /* Main program */ int Py_Main(int argc, char **argv) { int c; int sts; char *command = NULL; char *filename = NULL; char *module = NULL; FILE *fp = stdin; char *p; int unbuffered = 0; int skipfirstline = 0; int stdin_is_interactive = 0; int help = 0; int version = 0; int saw_unbuffered_flag = 0; PyCompilerFlags cf; cf.cf_flags = 0; orig_argc = argc; /* For Py_GetArgcArgv() */ orig_argv = argv; #ifdef RISCOS Py_RISCOSWimpFlag = 0; #endif PySys_ResetWarnOptions(); while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { if (c == 'c') { /* -c is the last option; following arguments that look like options are left for the command to interpret. */ command = (char *)malloc(strlen(_PyOS_optarg) + 2); if (command == NULL) Py_FatalError( "not enough memory to copy -c argument"); strcpy(command, _PyOS_optarg); strcat(command, "\n"); break; } if (c == 'm') { /* -m is the last option; following arguments that look like options are left for the module to interpret. */ module = (char *)malloc(strlen(_PyOS_optarg) + 2); if (module == NULL) Py_FatalError( "not enough memory to copy -m argument"); strcpy(module, _PyOS_optarg); break; } switch (c) { case 'b': Py_BytesWarningFlag++; break; case 'd': Py_DebugFlag++; break; case '3': Py_Py3kWarningFlag++; if (!Py_DivisionWarningFlag) Py_DivisionWarningFlag = 1; break; case 'Q': if (strcmp(_PyOS_optarg, "old") == 0) { Py_DivisionWarningFlag = 0; break; } if (strcmp(_PyOS_optarg, "warn") == 0) { Py_DivisionWarningFlag = 1; break; } if (strcmp(_PyOS_optarg, "warnall") == 0) { Py_DivisionWarningFlag = 2; break; } if (strcmp(_PyOS_optarg, "new") == 0) { /* This only affects __main__ */ cf.cf_flags |= CO_FUTURE_DIVISION; /* And this tells the eval loop to treat BINARY_DIVIDE as BINARY_TRUE_DIVIDE */ _Py_QnewFlag = 1; break; } fprintf(stderr, "-Q option should be `-Qold', " "`-Qwarn', `-Qwarnall', or `-Qnew' only\n"); return usage(2, argv[0]); /* NOTREACHED */ case 'i': Py_InspectFlag++; Py_InteractiveFlag++; break; /* case 'J': reserved for Jython */ case 'O': Py_OptimizeFlag++; break; case 'B': Py_DontWriteBytecodeFlag++; break; case 's': Py_NoUserSiteDirectory++; break; case 'S': Py_NoSiteFlag++; break; case 'E': Py_IgnoreEnvironmentFlag++; break; case 't': Py_TabcheckFlag++; break; case 'u': unbuffered++; saw_unbuffered_flag = 1; break; case 'v': Py_VerboseFlag++; break; #ifdef RISCOS case 'w': Py_RISCOSWimpFlag = 1; break; #endif case 'x': skipfirstline = 1; break; /* case 'X': reserved for implementation-specific arguments */ case 'U': Py_UnicodeFlag++; break; case 'h': case '?': help++; break; case 'V': version++; break; case 'W': PySys_AddWarnOption(_PyOS_optarg); break; /* This space reserved for other options */ default: return usage(2, argv[0]); /*NOTREACHED*/ } } if (help) return usage(0, argv[0]); if (version) { fprintf(stderr, "Python %s\n", PY_VERSION); return 0; } if (Py_Py3kWarningFlag && !Py_TabcheckFlag) /* -3 implies -t (but not -tt) */ Py_TabcheckFlag = 1; if (!Py_InspectFlag && (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') Py_InspectFlag = 1; if (!saw_unbuffered_flag && (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') unbuffered = 1; if (!Py_NoUserSiteDirectory && (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') Py_NoUserSiteDirectory = 1; if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { char *buf, *warning; buf = (char *)malloc(strlen(p) + 1); if (buf == NULL) Py_FatalError( "not enough memory to copy PYTHONWARNINGS"); strcpy(buf, p); for (warning = strtok(buf, ","); warning != NULL; warning = strtok(NULL, ",")) PySys_AddWarnOption(warning); free(buf); } if (command == NULL && module == NULL && _PyOS_optind < argc && strcmp(argv[_PyOS_optind], "-") != 0) { #ifdef __VMS filename = decc$translate_vms(argv[_PyOS_optind]); if (filename == (char *)0 || filename == (char *)-1) filename = argv[_PyOS_optind]; #else filename = argv[_PyOS_optind]; #endif } stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); if (unbuffered) { #if defined(MS_WINDOWS) || defined(__CYGWIN__) _setmode(fileno(stdin), O_BINARY); _setmode(fileno(stdout), O_BINARY); #endif #ifdef HAVE_SETVBUF setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); #else /* !HAVE_SETVBUF */ setbuf(stdin, (char *)NULL); setbuf(stdout, (char *)NULL); setbuf(stderr, (char *)NULL); #endif /* !HAVE_SETVBUF */ } else if (Py_InteractiveFlag) { #ifdef MS_WINDOWS /* Doesn't have to have line-buffered -- use unbuffered */ /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); #else /* !MS_WINDOWS */ #ifdef HAVE_SETVBUF setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); #endif /* HAVE_SETVBUF */ #endif /* !MS_WINDOWS */ /* Leave stderr alone - it should be unbuffered anyway. */ } #ifdef __VMS else { setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); } #endif /* __VMS */ #ifdef __APPLE__ /* On MacOS X, when the Python interpreter is embedded in an application bundle, it gets executed by a bootstrapping script that does os.execve() with an argv[0] that's different from the actual Python executable. This is needed to keep the Finder happy, or rather, to work around Apple's overly strict requirements of the process name. However, we still need a usable sys.executable, so the actual executable path is passed in an environment variable. See Lib/plat-mac/bundlebuiler.py for details about the bootstrap script. */ if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') Py_SetProgramName(p); else Py_SetProgramName(argv[0]); #else Py_SetProgramName(argv[0]); #endif Py_Initialize(); if (Py_VerboseFlag || (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { fprintf(stderr, "Python %s on %s\n", Py_GetVersion(), Py_GetPlatform()); if (!Py_NoSiteFlag) fprintf(stderr, "%s\n", COPYRIGHT); } if (command != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ _PyOS_optind--; argv[_PyOS_optind] = "-c"; } if (module != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' so that PySys_SetArgv correctly sets sys.path[0] to '' rather than looking for a file called "-m". See tracker issue #8202 for details. */ _PyOS_optind--; argv[_PyOS_optind] = "-c"; } PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && isatty(fileno(stdin))) { PyObject *v; v = PyImport_ImportModule("readline"); if (v == NULL) PyErr_Clear(); else Py_DECREF(v); } if (command) { sts = PyRun_SimpleStringFlags(command, &cf) != 0; free(command); } else if (module) { sts = RunModule(module, 1); free(module); } else { if (filename == NULL && stdin_is_interactive) { Py_InspectFlag = 0; /* do exit on SystemExit */ RunStartupFile(&cf); } /* XXX */ sts = -1; /* keep track of whether we've already run __main__ */ if (filename != NULL) { sts = RunMainFromImporter(filename); } if (sts==-1 && filename!=NULL) { if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n", argv[0], filename, errno, strerror(errno)); return 2; } else if (skipfirstline) { int ch; /* Push back first newline so line numbers remain the same */ while ((ch = getc(fp)) != EOF) { if (ch == '\n') { (void)ungetc(ch, fp); break; } } } { /* XXX: does this work on Win/Win64? (see posix_fstat) */ struct stat sb; if (fstat(fileno(fp), &sb) == 0 && S_ISDIR(sb.st_mode)) { fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename); fclose(fp); return 1; } } } if (sts==-1) { /* call pending calls like signal handlers (SIGINT) */ if (Py_MakePendingCalls() == -1) { PyErr_Print(); sts = 1; } else { sts = PyRun_AnyFileExFlags( fp, filename == NULL ? "<stdin>" : filename, filename != NULL, &cf) != 0; } } } /* Check this environment variable at the end, to give programs the * opportunity to set it from Python. */ if (!Py_InspectFlag && (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') { Py_InspectFlag = 1; } if (Py_InspectFlag && stdin_is_interactive && (filename != NULL || command != NULL || module != NULL)) { Py_InspectFlag = 0; /* XXX */ sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0; } Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */ #endif #ifdef __INSURE__ /* Insure++ is a memory analysis tool that aids in discovering * memory leaks and other memory problems. On Python exit, the * interned string dictionary is flagged as being in use at exit * (which it is). Under normal circumstances, this is fine because * the memory will be automatically reclaimed by the system. Under * memory debugging, it's a huge source of useless noise, so we * trade off slower shutdown for less distraction in the memory * reports. -baw */ _Py_ReleaseInternedStrings(); #endif /* __INSURE__ */ return sts; } Good God Almighty...it is big enough to sink the Titanic. It seems as though Python did the "Intro to Programming 101" trick and just moved all of main()'s code to a different function called it something very similar to "main". Here's my question: Is this code terribly written, or are there other reasons to have a short main function? As it stands right now, I see absolutely no difference between doing this and just moving the code in Py_Main() back into main(). Am I wrong in thinking this?

    Read the article

  • Why are static classes considered “classes” and “reference types”?

    - by Timwi
    I’ve been pondering about the C# and CIL type system today and I’ve started to wonder why static classes are considered classes. There are many ways in which they are not really classes: A “normal” class can contain non-static members, a static class can’t. In this respect, a class is more similar to a struct than it is to a static class, and yet structs have a separate name. You can have a reference to an instance of a “normal” class, but not a static class (despite it being considered a “reference type”). In this respect, a class is more similar to an interface than it is to a static class, and yet interfaces have a separate name. The name of a static class can never be used in any place where a type name would normally fit: you can’t declare a variable of this type, you can’t use it as a base type, and you can’t use it as a generic type parameter. In this respect, static classes are somewhat more like namespaces. A “normal” class can implement interfaces. Once again, that makes classes more similar to structs than to static classes. A “normal” class can inherit from another class. It is also bizarre that static classes are considered to derive from System.Object. Although this allows them to “inherit” the static methods Equals and ReferenceEquals, the purpose of that inheritance is questionable as you would call those methods on object anyway. C# even allows you to specify that useless inheritance explicitly on static classes, but not on interfaces or structs, where the implicit derivation from object and System.ValueType, respectively, actually has a purpose. Regarding the subset-of-features argument: Static classes have a subset of the features of classes, but they also have a subset of the features of structs. All of the things that make a class distinct from the other kinds of type, do not seem to apply to static classes. Regarding the typeof argument: Making a static class into a new and different kind of type does not preclude it from being used in typeof. Given the sheer oddity of static classes, and the scarcity of similarities between them and “normal” classes, shouldn’t they have been made into a separate kind of type instead of a special kind of class?

    Read the article

  • Variables in static library are never initialized. Why?

    - by Coyote
    I have a bunch of variables that should be initialized then my game launches, but must of them are never initialized. Here is an example of the code: MyClass.h class MyClass : public BaseObject { DECLARE_CLASS_RTTI(MyClass, BaseObject); ... }; MyClass.cpp REGISTER_CLASS(MyClass) Where REGISTER_CLASS is a macro defined as follow #define REGISTER_CLASS(className)\ class __registryItem##className : public __registryItemBase {\ virtual className* Alloc(){ return NEW className(); }\ virtual BaseObject::RTTI& GetRTTI(){ return className::RTTI; }\ }\ \ const __registryItem##className __registeredItem##className(#className); and __registryItemBase looks like this: class __registryItemBase { __registryItemBase(const _string name):mName(name){ ClassRegistry::Register(this); } const _string mName; virtual BaseObject* Alloc() = 0; virtual BaseObject::RTTI& GetRTTI() = 0; } Now the code is similar to what I currently have and what I have works flawlessly, all the registered classes are registered to a ClassManager before main(...) is called. I'm able to instantiate and configure components from scripts and auto-register them to the right system etc... The problem arrises when I create a static library (currently for the iPhone, but I fear it will happen with android as well). In that case the code in the .cpp files is never registered. Why is the resulting code not executed when it is in the library while the same code in the program's binary is always executed? Bonus questions: For this to work in the static library, what should I do? Is there something I am missing? Do I need to pass a flag when building the lib? Should I create another structure and init all the __registeredItem##className using that structure?

    Read the article

  • Creating an Objective-C++ Static Library in Xcode

    - by helixed
    So I've developed an engine for the iPhone with which I'd like to build a couple different games. Rather than copy and paste the files for the engine inside of each game's project directory, I'd a way to link to the engine from each game, so if I need to make a change to it I only have to do so once. After reeding around a little bit, it seems like static libraries are the best way to do this on the iPhone. I created a new project called Skeleton and copied all of my engine files over to it. I used this guide to create a static library, and I imported the library into a project called Chooser. However, when I tried to compile the project, Xcode started complaining about some C++ data structures I included in a file called ControlScene.mm. Here's my build errors: "operator delete(void*)", referenced from: -[ControlScene dealloc] in libSkeleton.a(ControlScene.o) -[ControlScene init] in libSkeleton.a(ControlScene.o) __gnu_cxx::new_allocator<operation_t>::deallocate(operation_t*, unsigned long)in libSkeleton.a(ControlScene.o) __gnu_cxx::new_allocator<operation_t*>::deallocate(operation_t**, unsigned long)in libSkeleton.a(ControlScene.o) "operator new(unsigned long)", referenced from: -[ControlScene init] in libSkeleton.a(ControlScene.o) __gnu_cxx::new_allocator<operation_t*>::allocate(unsigned long, void const*)in libSkeleton.a(ControlScene.o) __gnu_cxx::new_allocator<operation_t>::allocate(unsigned long, void const*)in libSkeleton.a(ControlScene.o) "std::__throw_bad_alloc()", referenced from: __gnu_cxx::new_allocator<operation_t*>::allocate(unsigned long, void const*)in libSkeleton.a(ControlScene.o) __gnu_cxx::new_allocator<operation_t>::allocate(unsigned long, void const*)in libSkeleton.a(ControlScene.o) "___cxa_rethrow", referenced from: std::_Deque_base<operation_t, std::allocator<operation_t> >::_M_create_nodes(operation_t**, operation_t**)in libSkeleton.a(ControlScene.o) std::_Deque_base<operation_t, std::allocator<operation_t> >::_M_initialize_map(unsigned long)in libSkeleton.a(ControlScene.o) "___cxa_end_catch", referenced from: std::_Deque_base<operation_t, std::allocator<operation_t> >::_M_create_nodes(operation_t**, operation_t**)in libSkeleton.a(ControlScene.o) std::_Deque_base<operation_t, std::allocator<operation_t> >::_M_initialize_map(unsigned long)in libSkeleton.a(ControlScene.o) "___gxx_personality_v0", referenced from: ___gxx_personality_v0$non_lazy_ptr in libSkeleton.a(ControlScene.o) ___gxx_personality_v0$non_lazy_ptr in libSkeleton.a(MenuLayer.o) "___cxa_begin_catch", referenced from: std::_Deque_base<operation_t, std::allocator<operation_t> >::_M_create_nodes(operation_t**, operation_t**)in libSkeleton.a(ControlScene.o) std::_Deque_base<operation_t, std::allocator<operation_t> >::_M_initialize_map(unsigned long)in libSkeleton.a(ControlScene.o) ld: symbol(s) not found collect2: ld returned 1 exit status If anybody could offer some insight as to why these problems are occuring, I'd appreciate it. Thanks, helixed

    Read the article

  • Static method not called

    - by Smile
    I'm trying to call a static method (printABC()) in this class but it's not working. If I uncomment both of the lines marked T_T (1 and 2), it works! Why does it fail with only one of the lines? import java.util.Scanner; class pro0009 { static Scanner in = new Scanner(System.in); static int A,B,C; static void printABC(){ String ABC = in.nextLine(); ABC=ABC.replace("A"," "+A+" "); ABC=ABC.replace("B"," "+B+" "); ABC=ABC.replace("C"," "+C+" "); //System.out.print(ABC.substring(1)); System.out.print(ABC); } public static void main(String[] args){ int x = in.nextInt(); //1 int y = in.nextInt(); //2 int z = in.nextInt(); //3 if(x<y){//1<2 if(x<z){ //1<3 if(y<z){//x<y<z 2<3 //1<2<3 A=x; B=y; C=z; printABC();//T_T 1 System.out.println("Here"); //pro0009.printABC();//T_T 2 //System.out.println("Here2"); }else{ //x<z<y A=x; B=z; C=y; } }else{//z<x<y A=z; B=x; C=y; } }else{//y<x if(y<z){ if(x<z){//y<x<z A=y; B=x; C=z; }else{//y<z<x A=y; B=z; C=x; } }else{//z<y<x A=z; B=y; C=x; } } } }

    Read the article

  • android sdk main.out.xml parsing error?

    - by mobibob
    I just started a new Android project, "WeekendStudy" to continue learning Android development and I got stumped compiling the default 'hello weekendstudy' compile / run. I think that I missed a step in configuration and setup, but I am at a loss to find out where. I have an AVD configured, set and launched. When I press 'run', the SDK is building a file main.out.xml and then fails as this: [2010-03-06 09:46:47 - WeekendStudy]Error in an XML file: aborting build. [2010-03-06 09:46:48 - WeekendStudy]res/layout/main.xml:0: error: Resource entry main is already defined. [2010-03-06 09:46:48 - WeekendStudy]res/layout/main.out.xml:0: Originally defined here. [2010-03-06 09:46:48 - WeekendStudy]/Users/mobibob/Projects/workspace-weekend/WeekendStudy/res/layout/main.out.xml:1: error: Error parsing XML: no element found [2010-03-06 09:48:16 - WeekendStudy]Error in an XML file: aborting build. [2010-03-06 09:48:16 - WeekendStudy]res/layout/main.xml:0: error: Resource entry main is already defined. [2010-03-06 09:48:16 - WeekendStudy]res/layout/main.out.xml:0: Originally defined here. [2010-03-06 09:48:16 - WeekendStudy]/Users/mobibob/Projects/workspace-weekend/WeekendStudy/res/layout/main.out.xml:1: error: Error parsing XML: no element found [2010-03-06 09:55:29 - WeekendStudy]res/layout/main.xml:0: error: Resource entry main is already defined. [2010-03-06 09:55:29 - WeekendStudy]res/layout/main.out.xml:0: Originally defined here. [2010-03-06 09:55:29 - WeekendStudy]/Users/mobibob/Projects/workspace-weekend/WeekendStudy/res/layout/main.out.xml:1: error: Error parsing XML: no element found [2010-03-06 09:55:49 - WeekendStudy]Error in an XML file: aborting build. [2010-03-06 09:55:49 - WeekendStudy]res/layout/main.xml:0: error: Resource entry main is already defined. [2010-03-06 09:55:49 - WeekendStudy]res/layout/main.out.xml:0: Originally defined here. [2010-03-06 09:55:49 - WeekendStudy]/Users/mobibob/Projects/workspace-weekend/WeekendStudy/res/layout/main.out.xml:1: error: Error parsing XML: no element found

    Read the article

  • Problem using delegates, static, and dependencyproperties

    - by red-X
    I'm trying to animate a private variable named radius, which works. However while its changing I'm trying to execute a function which is getting to be quite of a problem. the code i have is below, it wont run because it has the following error An object reference is required for the non-static field, method, or property 'AppPart.SetChildrenPosition()' specifically new SetChildrenPositionDelegate(SetChildrenPosition) this part in this sentance part.Dispatcher.BeginInvoke(new SetChildrenPositionDelegate(SetChildrenPosition), new Object()); thnx to anyone able to help me. class AppPart : Shape { public string name { get; set; } public List<AppPart> parts { get; set; } private double radius { get { return (double)GetValue(radiusProperty); } set { SetValue(radiusProperty, value); } } public static readonly DependencyProperty radiusProperty = DependencyProperty.Register( "radius", typeof(double), typeof(AppPart), new PropertyMetadata( new PropertyChangedCallback(radiusChangedCallback))); private delegate void SetChildrenPositionDelegate(); private void SetChildrenPosition() { //do something with radius } private static void radiusChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { AppPart part = d as AppPart; part.Dispatcher.BeginInvoke(new SetChildrenPositionDelegate(SetChildrenPosition), new Object()); } private void AnimateRadius(double start, double end) { DoubleAnimation ani = new DoubleAnimation(); ani.From = start; ani.To = end; ani.FillBehavior = FillBehavior.HoldEnd; ani.Duration = new Duration(new TimeSpan(0, 0, 0, 3, 0)); ani.Completed += delegate { Console.WriteLine("ani ended"); }; this.BeginAnimation(AppPart.radiusProperty, ani); } }

    Read the article

  • Accessing Static Methods on a Generic class in c#

    - by mrlane
    Hello, I have the following situation in code, which I suspect may be a bit dodgey: I have a class: abstract class DataAccessBase<T> : IDataAccess where T : AnotherAbstractClass This class DataAccessBase also has a static factory method which creates instances of derived classes of itself using an enum value in a which statement to decide which derived type to create: static IDataAccess CreateInstance(TypeToCreateEnum) Now, the types derived from DataAccessBase<T> are themselves NOT generic, they specify a type for T: class PoLcZoneData : DataAccessBase<PoLcZone> // PoLcZone is derived from AnotherAbstractClass So far I am not sure if this is pushing the limits of good use of generics, but what I am really concerned about is how to access the static CreateInstance() method in the first place: The way I am doing this at the moment is to simply pass any type T where T : AnotherAbstractClass. In particular I am passing AnotherAbstractClass itself. This allows compilation just fine, but it does seem to me that passing any type to a generic class just to get at the statics is a bit dodgey. I have actually simplified the situation somewhat as DataAccessBase<T> is the lower level in the inheritance chain, but the static factory methods exists in a middle tier with classes such as PoLcZoneData being the most derived on the only level that is not generic. What are peoples thoughts on this arrangement?

    Read the article

  • Thread-safe initialization of function-local static const objects

    - by sbi
    This question made me question a practice I had been following for years. For thread-safe initialization of function-local static const objects I protect the actual construction of the object, but not the initialization of the function-local reference referring to it. Something like this: namspace { const some_type& create_const_thingy() { lock my_lock(some_mutex); static const some_type the_const_thingy; return the_const_thingy; } } void use_const_thingy() { static const some_type& the_const_thingy = create_const_thingy(); // use the_const_thingy } The idea is that locking takes time, and if the reference is overwritten by several threads, it won't matter. I'd be interested if this is safe enough in practice? safe according to The Rules? (I know, the current standard doesn't even know what "concurrency" is, but what about trampling over an already initialized reference? And do other standards, like POSIX, have something to say that's relevant to this?) For the inquiring minds: Many such function-local static const objects I used are maps which are initialized from const arrays upon first use and used for lookup. For example, I have a few XML parsers where tag name strings are mapped to enum values, so I could later switch over the tags enum values.

    Read the article

  • NPE annotation scenarios and static-analysis tools for Java

    - by alex2k8
    Here is a number of code snippets that can throw NullPointerException. 01: public void m1(@Nullable String text) { System.out.print(text.toLowerCase()); // <-- expect to be reported. } 02: private boolean _closed = false; public void m1(@Nullable String text) { if(_closed) return; System.out.print(text.toLowerCase()); // <-- expect to be reported. } 03: public void m1(@NotNull String text) { System.out.print(text.toLowerCase()); } public @Nullable String getText() { return "Some text"; } public void m2() { m1(getText()); // <-- expect to be reported. } Different people have access to different static-analysis tools. It would be nice to collect information, what tools are able to detect and report the issues, and what are failing. Also, if you have your own scenarious, please, publish them. Here my results FindBugs (1.3.9): 01: Parameter must be nonnull but is marked as nullable 02: NOT reported 03: NOT reported IntelliJ IDE 9.0.2 (Community edition): 01: Method invocation text.toLowerCase() may produce java.lang.NullPointerException 02: Method invocation text.toLowerCase() may produce java.lang.NullPointerException 03: Argument getText() might be null

    Read the article

  • How do I cast a void pointer to a struct in C?

    - by Rowhawn
    In a project I'm writing code for, I have a void pointer, "implementation", which is a member of a "Hash_map" struct, and points to an "Array_hash_map" struct. The concepts behind this project are not very realistic, but bear with me. The specifications of the project ask that I cast the void pointer "implementation" to an "Array_hash_map" before I can use it in any functions. My question, specifically is, what do I do in the functions to cast the void pointers to the desired struct? Is there one statement at the top of each function that casts them or do I make the cast every time I use "implementation"? Here are the typedefs the structs of a Hash_map and Array_hash_map as well as a couple functions making use of them. typedef struct { Key_compare_fn key_compare_fn; Key_delete_fn key_delete_fn; Data_compare_fn data_compare_fn; Data_delete_fn data_delete_fn; void *implementation; } Hash_map; typedef struct Array_hash_map{ struct Unit *array; int size; int capacity; } Array_hash_map; typedef struct Unit{ Key key; Data data; } Unit; functions: /* Sets the value parameter to the value associated with the key parameter in the Hash_map. */ int get(Hash_map *map, Key key, Data *value){ int i; if (map == NULL || value == NULL) return 0; for (i = 0; i < map->implementation->size; i++){ if (map->key_compare_fn(map->implementation->array[i].key, key) == 0){ *value = map->implementation->array[i].data; return 1; } } return 0; } /* Returns the number of values that can be stored in the Hash_map, since it is represented by an array. */ int current_capacity(Hash_map map){ return map.implementation->capacity; }

    Read the article

  • Weak-linking with static libraries

    - by Jaakko L.
    I have declared an external function with a GCC weak attribute in a .c file: extern int weakFunction( ) __attribute__ ((weak)); Compiled object file has weakFunction defined as a weak symbol. Output of nm: 1791: w weakFunction I am calling the weak defined function as follows: if (weakFunction != NULL) { weakFunction(); } When I link the program by defining the object files as parameters to GCC (gcc main.o weakf.o -o main.exe) weak symbols work fine. If I leave the weakf.o out of linking, the function address is NULL in main.c and the function won't be called. Problem is, when weakf.o is inside a static library, for some reason the linker doesn't find the function and the function address always ends up being NULL. Static library is created with ar: ar rcs weaklibrary weakf.o Anyone had similar problems?

    Read the article

  • Categories in static library for iPhone device 3.0

    - by Nick
    I have categories in my static library. Any application developer should set -ObjC flag to "Other Linker Flags" to use my static library properly. It works fine for iPhone device/iPhone Simulator 2.x and iPhone Simulator 3.0. But it crashes for iPhone device 3.0. As written in this article it is new linker bug. They suggest to use one more linker flag: -all_load. But when I add this flag, build fails too, because there are duplicate symbols. How to use categories in static libraries for iPhone device 3.0? Any suggestions?

    Read the article

  • DLL export of a static function

    - by Begbie00
    Hi all - I have the following static function: static inline HandVal StdDeck_StdRules_EVAL_N( StdDeck_CardMask cards, int n_cards ) Can I export this function in a DLL? If so, how? Thanks, Mike Background information: I'm doing this because the original source code came with a VS project designed to compile as a static (.lib) library. In order to use ctypes/Python, I'm converting the project to a DLL. I started a VS project as a DLL and imported the original source code. The project builds into a DLL, but none of the functions (including functions such as the one listed above) are exported (as confirmed by both the absence of dllexport in the source code and tools such as DLL Export Viewer). I tried to follow the general advice here (create an exportable wrapper function within the header) to no avail...functions still don't appear to be exported.

    Read the article

  • accessing a static property via COM

    - by joreg
    is it possible to access a static property of a COM object without creating an instance of the object? my situation is this: i have an unmanaged application (written in delphi). this application exposes a COM-based plugininterface. until now i only wrote managed plugins in c#. plugins provide their info (name, author, ..) via a static property that returns an instance of PluginInfo (which implements IPluginInfo). this static property i can access on the managed plugins using http://managedvcl.com. now i want to write unmanaged plugins on the same interface. i can load them using: plug := CreateComObject(TGuid) as IMyPlugInterface; and they run, but i don't know how to read out their PluginInfo. so the question again is: is there another way than implementing IPluginInfo in the plugin-class and only accessing the info after i have created an instance of the plugin?

    Read the article

  • .NET: will Random.Random operate differently inside a static method

    - by Craig Johnston
    I am having difficulty with the following code which is inside a static method of a non-static class. int iRand; int rand; rand = new Random((int)DateTime.Now.Ticks); iRand = rand.Next(50000); The iRand number, along with some other values, are being inserted into a new row of an Access MDB table via OLEDB. The iRand number is being inserted into a field that is part of the primary key, and the insert attempt is throwing the following exception even though the iRand number is supposed to be random: System.Data.OleDb.OleDbException: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again. Could the fact the method is static be making the iRand number stay the same, for some reason?

    Read the article

  • Java: startingPath as "public static final" exception

    - by HH
    [Updated] Thanks to polygenelubricants's reply, the real problem is the exception from the method getCanonicalPath() because I cannot include try-catch-loop there. $ cat StartingPath.java import java.util.*; import java.io.*; public class StartingPath { public static final String startingPath = (new File(".")).getCanonicalPath(); public static void main(String[] args){ System.out.println(startingPath); } } $ javac StartingPath.java StartingPath.java:5: unreported exception java.io.IOException; must be caught or declared to be thrown public static final String startingPath = (new File(".")).getCanonicalPath(); ^ 1 error

    Read the article

  • Returning in a static initializer

    - by Martijn Courteaux
    Hello, This isn't valid code: public class MyClass { private static boolean yesNo = false; static { if (yesNo) { System.out.println("Yes"); return; // The return statement is the problem } System.exit(0); } } This is a stupid example, but in a static class constructor we can't return;. Why? Are there good reasons for this? Does someone know something more about this? So the reason why I should do return is to end constructing there. Thanks

    Read the article

  • Finding C++ static initialization order problems

    - by Fred Larson
    We've run into some problems with the static initialization order fiasco, and I'm looking for ways to comb through a whole lot of code to find possible occurrences. Any suggestions on how to do this efficiently? Edit: I'm getting some good answers on how to SOLVE the static initialization order problem, but that's not really my question. I'd like to know how to FIND objects that are subject to this problem. Evan's answer seems to be the best so far in this regard; I don't think we can use valgrind, but we may have memory analysis tools that could perform a similar function. That would catch problems only where the initialization order is wrong for a given build, and the order can change with each build. Perhaps there's a static analysis tool that would catch this. Our platform is IBM XLC/C++ compiler running on AIX.

    Read the article

  • Returning in a static class constructor

    - by Martijn Courteaux
    Hello, This isn't valid code: public class MyClass { private static boolean yesNo = false; static { if (yesNo) { System.out.println("Yes"); return; // The return statement is the problem } System.exit(0); } } This is a stupid example, but in a static class constructor we can't return;. Why? Are there good reasons for this? Does someone know something more about this? So the reason why I should do return is to end constructing there. Thanks

    Read the article

  • Why is this static routing not working ?

    - by geeko
    Greeting gurus, I'm trying to develop a DHCP enforcement extension like Microsoft NAP. My trick to block dynamic-IP requesting machines (that don't meet certain policy) is to strip the default gateway (no default gateway) stated in the IP lease and set the lease subnet mask to 255.255.255.255. Now I need the blocked machines to be able to reach some specific locations (IPs) on the network. To allow for this, I'm including some static routes in the lease. For example, I'm including 10.10.10.11 via router 10.10.10.254 (the one to which the blocked machine that needs to access 10.10.10.11 is connected). Unfortunately, as soon as I set the default gateway to nothing, blocked machines cannot reach any of the added static routes. I also tried classless static routes. Any ideas ? any one knows how MS NAP actually do it ? Geeko

    Read the article

  • Exposing headers on iPhone static library

    - by leolobato
    Hello guys, I've followed this tutorial for setting up a static library with common classes from 3 projects we are working on. It's pretty simple, create a new static library project on xcode, add the code there, a change some headers role from project to public. The tutorial says I should add my library folder to the header search paths recursively. Is this the right way to go? I mean, on my library project, I have files separated in folders like Global/, InfoScreen/, Additions/. I was trying to setup one LOKit.h file on the root folder, and inside that file #import everything I need to expose. So on my host project I don't need to add the folder recursively to the header search path, and would just #import "LOKit.h". But I couldn't get this to work, the host project won't build complaining about all the classes I didn't add to LOKit.h, even though the library project builds. So, my question is, what is the right way of exposing header files when I setup a Cocoa Touch Static Library project on xCode?

    Read the article

  • Static struct in C++

    - by pingvinus
    Hi, I want to define an structure, where some math constants would be stored. Here what I've got now: struct consts { //salt density kg/m3 static const double gamma; }; const double consts::gamma = 2350; It works fine, but there would be more than 10 floating point constants, so I doesn't want to wrote 'static const' before each of them. And define something like that: static const struct consts { //salt density kg/m3 double gamma; }; const double consts::gamma = 2350; It look fine, but I got these errors: 1. member function redeclaration not allowed 2. a nonstatic data member may not be defined outside its class I wondering if there any C++ way to do it?

    Read the article

  • c++ defining a static member of a template class with type inner class pointer

    - by Jack
    I have a template class like here (in a header) with a inner class and a static member of type pointer to inner class template <class t> class outer { class inner { int a; }; static inner *m; }; template <class t> outer <t>::inner *outer <t>::m; when i want to define that static member i says "error: expected constructor, destructor, or type conversion before '*' token" on the last line (mingw32-g++ 3.4.5)

    Read the article

  • C++ Class Static variable problem - C programmer new to C++

    - by Microkernel
    Hi guys, I am a C programmer, but had learnt C++ @school longtime back. Now I am trying to write code in C++ but getting compiler error. Please check and tell me whats wrong with my code. typedef class _filter_session { private: static int session_count; /* Number of sessions count -- Static */ public: _filter_session(); /* Constructor */ ~_filter_session(); /* Destructor */ }FILTER_SESSION; _filter_session::_filter_session(void) { (this->session_count)++; return; } _filter_session::~_filter_session(void) { (this->session_count)--; return; } The error that I am getting is "error LNK2001: unresolved external symbol "private: static int _filter_session::session_count" (?session_count@_filter_session@@0HA)" I am using Visual Studio 2005 by the way. Plz plz help me. Regards, Microkernel

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >