C++ Destructors with Vectors, Pointers,

As far as I know, I should destroy in destructors everything I created with new and close opened filestreams and other streams. However, I have some doubts about other objects in C++:

  • std::vector and std::strings: Are they destroyed automatically?

  • If I have something like

    std::vector<myClass*> 
    

    of pointers to classes. What happens when the vector destructor is called? Would it call automatically the destructor of myClass? Or only the vector is destroyed but all the Objects it contains are still existant in the memory?

  • What happens if I have a pointer to another class inside a class, say:

    class A {
      ClassB* B;
    }
    

    and Class A is destroyed at some point in the code. Will Class B be destroyed too or just the pointer and class B will be still existent somewhere in the memory?

std::vector and std::strings: Are they destroyed automatically?

Yes (assuming member variables are not pointers to std::vector and std::string).

If I have something like std::vector what happens when the vector destructor is called? Would it call automatically the destructor of myClass? Or only the vector is destroyed but all the Objects it contains are still existant in the memory?

If vector<MyClass> then all objects contained in the vector will be destroyed. If vector<MyClass*> then all objects must be explicitly deleted (assuming the class being destructed owns the objects in the vector). A third alternative is vector of smart pointers, like vector<shared_ptr<MyClass>>, in which case the elements of the vector do not need to be explictly deleted.

What happens if I have a pointer to another class inside a class

The B must be explicitly deleted. Again, a smart pointer could be used to handle the destruction of B.

C Programming Tutorial for Beginners, Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C) C or c is the third letter in the English and ISO basic Latin alphabets. Its name in English is cee, plural cees.

You only need to worry about for the memory you have created dynamically (When you reserve memory with new.)

For example:

Class Myclass{
   private:
       char* ptr;
   public:
       ~Myclass() {delete[] ptr;};
}

"C" Programming Language: Brian Kernighan, This course will give you a full introduction into all of the core concepts in the C programming Duration: 3:46:13 Posted: Aug 15, 2018 Ç or ç is a Latin script letter, used in the Albanian, Azerbaijani, Manx, Tatar, Turkish, Turkmen, Kurdish, Zazaki, and Romance alphabets. Romance languages that use this letter include Catalan, French, Friulian, Ligurian, Occitan, and Portuguese as a variant of the letter C. It is also occasionally used in Crimean Tatar and in Tajik to represent the /d͡ʒ/ sound. It is often retained in the spelling of loanwords from any of these languages in English, Basque, Dutch, Spanish and other

It depends. std::vector and std::string and MyClass all have 1 thing in common - if you declare a variable to be any of those types, then it will be allocated on stack, be local to the current block you're in, and be destructed when that block ends.

E.g.

{
    std::vector<std::string> a;
    std::string b;
    MyClass c;
} //at this point, first c will be destroyed, then b, then all strings in a, then a.

If you get to pointers, you guessed correctly: Only the memory the pointer itself occupies (usually a 4 byte integer) will be automatically freed upon leaving scope. Nothing happens to the memory pointed to unless you explicitly delete it (whether it's in a vector or not). If you have a class that contains pointers to other objects you may have to delete them in the destructor (depending on whether or not that class owns those objects). Note that in C++11 there are pointer classes (called smart pointers) that let you treat pointers in a similar fashion to 'normal' objects:

Ex:

{
    std::unique_ptr<std::string> a = make_unique<std::string>("Hello World");
    function_that_wants_string_ptr(a.get());
} //here a will call delete on it's internal string ptr and then be destroyed

How easy is it to learn C?, "C" is one of the most widely used programming languages of all time. Prof Brian Kernighan Duration: 8:26 Posted: Aug 18, 2015 Stock analysis for Citigroup Inc (C:New York) including stock price, stock chart, company news, key statistics, fundamentals and company profile.

How is C programming language still used today?, - and extremely flexible. So flexible, in fact, that as you use the language, you probably go through many different programming styles as you work out how to use the language to produce good, maintainable, reliable code. C-- (pronounced cee minus minus) is a C -like programming language. Its creators, functional programming researchers Simon Peyton Jones and Norman Ramsey, designed it to be generated mainly by compilers for very high-level languages rather than written by human programmers.

If I have something like std::vector what happens when the vector destructor is called?

It depends.

If you have a vector of values std::vector <MyClass>, then the destructor of the vector calls the destructor for every instance of MyClass in the vector.

If you have a vector of pointers std::vector <MyClass*>, then you're responsible for deleting the instances of MyClass.

What happens if I have a pointer to another class inside a class

ClassB instance would remain in memory. Possible ways to have ClassA destructor to make the job for you are to make B an instance member or a smart pointer.

Which programs are written in C language?, is best choice when you start programming as it is most basic. This is a list of operators in the C and C++ programming languages.All the operators listed exist in C++; the fourth column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.. When not overloaded, for the operators &&, ||, and , (the comma operator), there is a sequence point after the evaluation of the first operand.

Learn C, . Some of the examples are operating systems, more specifically OS kernels, device drivers and interfaces, etc. As well as C and Simula's influences, other languages also influenced this new language, including ALGOL 68, Ada, CLU and ML . Initially, Stroustrup's "C with Classes" added features to the C compiler, Cpre, including classes, derived classes, strong typing, inlining and default arguments.

C Tutorial, learn-c.org is a free interactive C tutorial for people who want to learn C, fast. C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs.C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This C++ tutorial adopts a simple and practical approach to describe the concepts of C++ for beginners to advanded software engineers.. Why to Learn C++. C++ is a MUST for students and working

C Language - Overview, C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone  Learn C# programming - for beginning developers, developers new to C#, and experienced C# / .NET developers

Comments
  • "Or only the vector is destroyed but all the Objects it contains are still existant in the memory?" - fix your thinking here. The objects contained by a vector<myClass*> are myClass* objects, that is to say objects of pointer type. They are destroyed when the vector is destroyed, but destroying a pointer does not affect the object that the pointer points to. So the objects that the vector contains are not still existent in memory. Imagining that the objects pointed to by the pointers are "contained in the vector" is obstructing you from being able to answer your own question :-)
  • Incidentally, you should use the add comment links below each answer to respond to them or ask for clarification. Don't use the Post Your Answer link!
  • shared_ptr is not provided. should I download something? Boost?
  • @ISTB, yes. There is boost::shared_ptr and boost::scoped_ptr. C++11 added smart pointers std::shared_ptr and std::unique_ptr (#include <memory>).
  • By the way, if I am using shared_ptr, how can I use new? I think that shared_ptr<ClassA> a = new ClassA(); will not work
  • @ISTB, you shared_ptr<ClassA> a(new ClassA()); or shared_ptr<ClassA> a = make_shared<ClassA>();
  • And what happens if later I have a vector<std::shared_ptr<ClassA>> in whicH I push the ClassA objects by using shared_ptr<ClassA> a(new ClassA()); and then I call vector.clear(), will it destroy the ClassA objects created by new and pushed into the vector?
  • if the class member is pointer and public, is it better "new" and "delete" in the same class ? (Because it's more clearly to read the code)
  • How can make_unique("Hello World") ever result in a std::unique_ptr<std::string> (without crazy expression template stuff)? Did you mean make_unique<std::string>("Hello World") (assuming a sane make_unique function)?
  • Sorry, my fault just somehow assumed that would exist. There's a sane implementation that's not crazy though stackoverflow.com/questions/7038357/…
  • That still requires you to specify the type to be constructed by make_unique.
  • Yep, that was an oversight of mine.
  • So, practically the only problem is when I use pointers. As long as I use them, I have to destroy everything myself. Except if I am using smart pointers
  • @ISTB. You're right. See the answer from Luchian Grigore for a better explanation.
  • @ISTB: The problem is when you use raw owning pointers to dynamically allocated objects, which you should never be doing, in a vector or otherwise. Owning pointers should always be smart pointers, but raw pointers can still be used as non-owning reassignable references.