Question

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?

Était-ce utile?

La solution

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.

Autres conseils

You can't bind temporary rvalue to a non-const lvalue reference, and so you can't pass it as the argument to swap. However, you can call a member function on a temporary, so this will work:

decltype(v)().swap(v);

In C++11, it would be clearer to move from the temporary:

v = decltype(v)();

or use shrink_to_fit

v.clear();
v.shrink_to_fit();

(Note that, if you don't have C++11, then you don't have decltype, so the question is moot).

You may do (C++11):

v.clear();
v.shrink_to_fit();

or :

{
    decltype(v) tmp;

    v.swap(tmp);
}

vector::swap takes argument by reference. So temporary cannot be used here.

To clarify, decltype(v)() is the valid syntax for creating an unnamed temporary.
The source of the error, as the other answers explain, was that swap() does not work with the temporary returned by decltype(v)().

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top