这是合法的,以避免设置创建Comparator对象的实际副本

时间:2014-04-08 16:17:35

标签: c++ templates stl set functor

在这样的代码中:

Comparator comp(3);

set<string, Comparator> s1(comp);
set<string, Comparator> s2(comp);
set<string, Comparator> s3(comp);
set<string, Comparator> s4(comp); 

比较器的实际实例(即comp)在每次创建set对象时被复制为cpp引用状态

  

容器保留使用的alloc和comp的内部副本   分配存储并在整个生命周期内对元素进行排序。

所以我们想知道这在C ++中是否合法

#include <set>
#include <iostream>

struct A {
    int i = 0;
    bool operator()(int a, int b)
    {
        ++i;
        return a < b;
    }
};

int main()
{    
    A a;
    std::set<int, A&> s1( {1, 2, 3}, a);
    std::set<int, A&> s2( {4, 5, 6}, a);
    std::cout << a.i;
}

提前致谢。

1 个答案:

答案 0 :(得分:4)

我无法在标准中找到措辞,禁止使用引用类型作为比较函数。因此,这似乎是合法的。请注意,某些内容(例如默认构造此类集合)将被禁止,因为您的比较类型不是默认构造的。

最后请注意,规范的C ++方法是这样做,而是在外部维护状态。当你采取这种方法时,你完全清楚你正在做什么,并保证安全:

#include <set>
#include <iostream>

struct A {
    int& i_;
    explicit A(int& state) : i_(state) { }
    bool operator()(int a, int b)
    {
        ++i_;
        return a < b;
    }
};

int main() {
    int i;
    std::set<int, A> s1( {1, 2, 3}, A(i));      
    std::set<int, A> s2( {4, 5, 6}, A(i));        
    std::cout << i << endl;
}