Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC 4.4/4.5 unique_ptr not work for unordered_set/unordered_map

Tags:

c++

gcc

c++11

g++

Is there any place I can confirm this? I am not sure if it is the problem of GCC or my code. For example, the following code doesn't compile:

#include <unordered_set>
#include <memory>
using namespace std;

int main() {
    unordered_set<unique_ptr<int> > s;
    unique_ptr<int> p(new int(0));
    s.insert(move(p));
    return 0;
}

The error message is too big and I don't want to put here. GCC version is 4.5.3, compiling flag is -std=gnu++0x. Also tested on 4.4.5.

like image 561
Kan Li Avatar asked Sep 08 '11 03:09

Kan Li


3 Answers

GCC 4.6.1 accepts your code as is and I see nothing wrong with it (i.e. the value_type of an associative container is required to be EmplaceInsertable and std::unique_ptr does not prevent that). Presumably this is a deficiency in GCC 4.5.

like image 98
Luc Danton Avatar answered Sep 21 '22 13:09

Luc Danton


Your code is correct. This is a known issue in GCC 4.5. It has been fixed in 4.6. See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=44436 . It affects ordered containers too (std::map, std::set etc). Probably the easiest workaround (at a slight performance penalty) would be to use std::shared_ptr instead of std::unique_ptr.

like image 22
cvoinescu Avatar answered Sep 22 '22 13:09

cvoinescu


I can confirm that this is an issue with GCC 4.4.5. Attempting to insert a unique_ptr into an std::set results in a long compiler error message which alludes to the fact that some function in the STL attempted to copy the unique_ptr:

error: deleted function [unique_ptr's copy ctor]... used here [g++-v4/bits/stl_tree.h:136].

The STL function in question is part of the internal tree structure of several STL classes, including std::set. It is also within a "__GXX_EXPERIMENTAL_CXX0X__" ifdef, which presumably means that GCC 4.4 doesn't officially support what we're trying to do.

If you don't want to upgrade to GCC 4.6 you could always wrap an std::vector and strategically check for and remove duplicates at certain points in your code.

like image 3
M. George Hansen Avatar answered Sep 20 '22 13:09

M. George Hansen