0

Like in the following example:

#include <vector>

class VectorContainer {
private:
  std::vector<int> v;

public:
  void AddStuffToVector() {
    this->v.push_back(4);
    this->v.push_back(3);
    this->v.push_back(2);
    this->v.push_back(6);
  }
};

int main() {
  VectorContainer a;
  a.AddStuffToVector();
  a = VectorContainer();
}

Will the items added to the vector inside a leak after reassignment?

gnevesdev
  • 47
  • 6
  • 1
    It really depends on what `VectorContainer` is. Please add more info or create a [mre] – NathanOliver Sep 02 '21 at 16:31
  • Effectively, you are asking if `VectorContainer` was well-written. We do not know. Where did you find this `VectorContainer`? – Drew Dormann Sep 02 '21 at 16:33
  • 2
    The code in your edit [does not compile](https://godbolt.org/z/r375E5G14). Perhaps you meant `VectorContainer a;` and not `VectorContainer a();` – Drew Dormann Sep 02 '21 at 16:36
  • There is no memory leak. You can really only get a memory leak when you use `new` (or something like it) and you forget to `delete` (or something like it). You didn't use `new` (or something like it) so you can't leak. – NathanOliver Sep 02 '21 at 16:38
  • Fixed the error – gnevesdev Sep 02 '21 at 16:39
  • @NathanOliver but doesn't the vector allocate heap variables? So when does it `delete` if I reassign without calling the `assign` method? – gnevesdev Sep 02 '21 at 16:44
  • 6
    Vector handles all of this for you. It's assignment operator will see that the vector has elements, so it will get rid of them correctly, and then allow the reassignment to happen. Basically, it just works. `vector` is called an RAII type, and it is built to correctly handle the memory that it is managing. The only problem you can have is if you call a function and you have violated that functions preconditions, like calling `front` on an empty vector. – NathanOliver Sep 02 '21 at 16:46
  • Handy reading: [What is meant by Resource Acquisition is Initialization (RAII)?](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) – user4581301 Sep 02 '21 at 16:50
  • FYI, you don't need the `this->` syntax to access member variables. The `this->` syntax is primarily used to distinguish between parameter names and member names, when they are the same (a good coding style will make this unnecessary). – Thomas Matthews Sep 02 '21 at 21:46

2 Answers2

2

The shown program does not leak memory.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

since the std::vector has defined a assignment operator (will suppressed bitwise copy assiment), so the compiler will generate a implicit assigment operator for your "VectorContainer" class, like:

VectorContainer& VectorContainer::operator=(const VectorContainer &rhs)
{
    v = rhs.v;
    return *this;
}
Exlife
  • 99
  • 6