diff options
author | Geoff Liu <g@geoffliu.me> | 2015-08-30 14:41:02 -0600 |
---|---|---|
committer | Geoff Liu <g@geoffliu.me> | 2015-08-30 14:41:02 -0600 |
commit | a230d76307ecbc0f53c4b359cdb90628720f915e (patch) | |
tree | c0ddfe0cdd95202c67a0494f614a6430b155d2a1 | |
parent | eb7e58d5fc649ed2713c7685539bd5edcd9e8ade (diff) |
More about temporary objects
-rw-r--r-- | c++.html.markdown | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/c++.html.markdown b/c++.html.markdown index e45c73c3..74bd8913 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -765,6 +765,22 @@ Foo f1 = fooSub; Foo f1; f1 = f2; + +// How to truly clear a container: +class Foo { ... }; +vector<Foo> v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// Following line sets size of v to 0, but destructors don't get called, +// and resources aren't released! +v.empty(); +v.push_back(Foo()); // New value is copied into the first Foo we inserted in the loop. + +// Truly destroys all values in v. See section about temporary object for +// explanation of why this works. +v.swap(vector<Foo>()); + ``` Further Reading: |