Create and destroy an object in a loop

后端 未结 3 771
傲寒
傲寒 2021-01-29 03:51

I am new to C++/stacko and want to principally:

  1. Create an object
  2. Read in an enormous amount of data for that
  3. After calculating that object\'s sc
3条回答
  •  萌比男神i
    2021-01-29 04:40

    You don't need to call the destructor of object1, it would be called at the end of the loop body.

    Technically, destructors are called at the end (right brace) of the block declaring the object.

    This is why the right brace } is sometimes jokingly called the most important statement in C++. A lot of things may happen at that time.

    It is however generally considered bad style to do real computations in constructors or destructors. You want them to "allocate" and "deallocate" resources. Read more about RAII and the rule of five (or of three).

    BTW, if an exception happens, the destructors between the throw and the matching catch are also triggered.

    Please learn more about C++ containers. You probably want your applicants class to use some. Maybe it should contain a field of some std::vector type.

    Also learn C++11 (or C++14), not some older version of the standard. So use a recent compiler (e.g. GCC 4.9 at least, as g++, or Clang/LLVM 3.5 at least, as clang++) with the -std=c++11 option (don't forget to enable warnings with -Wall -Wextra, debugging info with -g for debugging with gdb, but enable optimizations e.g. with -O2 at least, when benchmarking). Modern C++11 (or C++14) has several very important features (missing in previous standards) that are tremendously useful when programming in C++. You probably should also use make (here I explain why), see e.g. this and others examples. See also valgrind.

提交回复
热议问题