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?
Decltype gives the type information at compile time while typeid gives at runtime.
The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.
In the C++ programming language, decltype is a keyword used to query the type of an expression. Introduced in C++11, its primary intended use is in generic programming, where it is often difficult, or even impossible, to express types that depend on template parameters.
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With