Jer*_*ntu 5 c++ qt stl unique-ptr c++11
为了避免大量不必要的复制,我试图将 unique_ptr 存储在一对列表中。我正在使用一个简单的类 Test,它带有一个 QString;
我正在使用 VS2013 和 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
Run Code Online (Sandbox Code Playgroud)
由于失败,我尝试了:
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
Run Code Online (Sandbox Code Playgroud)
由于失败,我完全改为 STL 容器:
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
Run Code Online (Sandbox Code Playgroud)
这有效。我的结论是否正确,这些 Qt 容器不支持移动语义,而我必须使用 STL?
std::unique_ptr是不可复制的,所以对于 Qt 容器来说不行。
Qt 容器是在 std::move (甚至 std::string)成为事物之前创建的。
也许Qt6会有更好的支持。它准备打破一些东西,以便更好地与现代 C++ 集成。
OTOH,如果 std-containers 适合你,你也可以使用它们,除非你有一些特定的用例?