Create and destroy an object in a loop

后端 未结 3 737
傲寒
傲寒 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-29 04:54

    It is not necessary to delete object1.

    For every iteration of the loop, a new object object1 will be created (using default constructor) and destructed after the "cout" statement.

    0 讨论(0)
  • 2021-01-29 04:56

    Object one will be deleted automatically when it goes out of scope at the end bracket. You are already doing it. Be wary as if you create a pointer it will not be destructed when it goes out of scope. But your current code is working fine.

    http://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm

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