Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a temporary of decltype

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?

like image 548
Adi Shavit Avatar asked Mar 19 '14 15:03

Adi Shavit


People also ask

Is decltype runtime or compile time?

Decltype gives the type information at compile time while typeid gives at runtime.

What is the decltype of a function?

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.

What is decltype used for in C++?

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.

Is decltype evaluated at compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.


1 Answers

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.

like image 187
bames53 Avatar answered Sep 22 '22 06:09

bames53