November 22nd, 2019

How do I make a clone of a Windows Runtime vector in C++/WinRT?

Suppose you have a Windows Runtime vector, either an IVector<T> or an IVector­View<T>, and you want to clone it so that you can operate on the clone without affecting the original. For example, maybe you have an IVector­View<T>, which is read-only, and you want to clone it so you can make changes.

The naïve way would be to copy the vector:

// Code in italics is wrong.
IVector<Thing> original = GetTheThings();
IVector<Thing> clone = IVector<Thing>{ original };

This doesn’t work because IVector<T> and IVector­View<T> are interfaces, and copying an interface merely copies a reference to the same underlying object.

To get a brand new object, you need to create a brand new object.

IVector<Thing> original = GetTheThings();
std::vector<Thing> temp{ original.Size() };
original.GetMany(0, temp);
IVector<Thing> clone = single_threaded_vector(std::move(temp));

First, we create a temporary vector into which we will copy the contents of the original vector.

Next, we use the Get­Many method to read the entire contents of the original IVector into our temporary vector. Note that if the vector’s size can change asynchronously, then there’s a race condition if the size changes between the time we create the temporary vector and the time we fill it with goodies. Fixing that is left as en exercise.

Finally, we create a brand new IVector from our temporary vector.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.