本文介绍了这是合法的避免设置创建Comparator对象的实际副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的代码中:

Comparator comp(3);

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

Comparator的实际实例(即comp)在每次创建集合对象时被复制为cpp引用状态

the actual instance of the Comparator (namely comp) is copied at each creation of a set object as the cpp reference states

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

So we were wondering if this is legal in 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;
}

提前感谢。

推荐答案

我无法在标准中找到禁止使用引用类型作为比较函数的措辞。因此,这似乎是合法的。注意,某些事情,如默认构造这样的集合,将被禁止,因为你的比较类型不是默认可构造的。

I'm unable to find wording in the standard forbidding using a reference type as the comparison function. Thus it seems that this would be legal. Note that some things, such as default constructing such a set, will be forbidden because your comparison type is not default constructable.

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

Finally note that the canonical C++ approach is to not do this, but to maintain the state externally. When you take that approach it's totally clear what you're doing and guaranteed to be safe:

#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;
}

这篇关于这是合法的避免设置创建Comparator对象的实际副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:08