Jeruntu
Jeruntu

Reputation: 188

Is it possible to store unique_ptr in a QList of QPairs?

To avoid a lot of unnecessary copying I'm trying to store unique_ptr's in a list of pairs. I'm using a simple class Test which takes a QString;

I'm using VS2013 with Qt5.4

using std::unique_ptr;

QList<QPair<unique_ptr<Test>, unique_ptr<Test>>> list;

auto a = std::make_unique<Test>("a");
auto b = std::make_unique<Test>("b");

// First make a pair
auto pair = qMakePair(std::move(a), std::move(b));      // Fails
// Error C2280 - attempting to reference a deleted function

Because of failure I tried:

QList<std::pair<unique_ptr<Test>, unique_ptr<Test>>> list;
auto pair = std::make_pair(std::move(a), std::move(b)); // Succes
list.append(std::move(pair)); // Fails
// Error C2280 - attempting to reference a deleted function

Because of failure I changed completely to STL containters:

std::list<std::pair<unique_ptr<Test>, unique_ptr<Test>>> list;
auto pair = make_pair(std::move(a), std::move(b)); // Succes
list.push_back(std::move(pair)); // Succes

This works. Is my conclusion correct that these Qt containers don't support move semantics and I have to use STL instead?

Upvotes: 6

Views: 3800

Answers (1)

Macke
Macke

Reputation: 25680

std::unique_ptr is not copyable, so nope for Qt containers.

Qt containers where created way before std::move (or even std::string) became a thing.

OTOH, you might as well use the std-containers if they work for you, unless you had some specific use case in mind? Use shared_ptr<const std::vector> if you need immutability?

Update:

The reason is that Qt containers are copy-on-write, so they (implicitly and unnoticeable) share data between copies until they are modified. Thus their implementation require elements to be copyable.

Upvotes: 3

Related Questions