I have an object of some type, for example, std::vector<int> v;
Now, say, I want to verify that v
releases all its internal memory.
Prior to the C++11 shrink_to_fit()
method, the recommended/guaranteed way to do this is to swap()
with an empty std::vector<>
of the same type.
However, I don't want to specify the type of the object. I can use decltype
to specify the type, so I'd like to write something like this:
std::vector<int> v;
// use v....
v.swap(decltype(v)()); // Create a temporary of same type as v and swap with it.
^^
However, the code above does not work. I cannot seem to create a temporary of type decltype(v)
with an empty ctor (in this case).
Is there some other syntax for creating such a temporary?
The issue is that swap
takes an lvalue reference: You cannot pass a temporary to swap
. Instead you should switch it around so that you call the temporary's swap
member:
decltype(v)().swap(v);
Of course C++11 introduced the shrink_to_fit()
member so that the swap trick is no longer necessary.