1

我在给出参数时出现了一个奇怪的行为。我的方法的标题是:

class Acceptability {
  public:
    Graph* G;                               
    std::unordered_set<node>* community;    
    std::unordered_set<node>* shell;        
  public:
    Acceptability(Graph& G, std::unordered_set<node>& community,
                  std::unordered_set<node>& shell);
    virtual ~Acceptability();
    virtual double getValue(node v) = 0;
};
class NodeClusterSimilarity: public Acceptability {
  public:
    NodeClusterSimilarity(Graph& G, std::unordered_set<node>& community,
                          std::unordered_set<node>& shell);
    virtual ~NodeClusterSimilarity(); 
    virtual double getValue(node v);
};

这两个类的构造函数如下:

GreedyCommunityExpansion::Acceptability::Acceptability(
    Graph& G, std::unordered_set<node>& community,
    std::unordered_set<node>& shell) {
  this->G = &G;
  this->community = &community;
  this->shell = &shell;
}
GreedyCommunityExpansion::NodeClusterSimilarity::NodeClusterSimilarity(
    Graph& G, std::unordered_set<node>& community,
    std::unordered_set<node>& shell)
  : Acceptability(G, community, shell) {
}

NodeClusterSimilarity在测试我的实现时,我使用community {0}and创建了一个类型的对象shell {1,2,3}。然后我调用了该方法getValue(),令人惊讶的是:community传递参数后的大小是1(hurraaaaaaas !!!)但大小shell0:(([预期值显然是3]

谁能告诉我,怎么了?

4

1 回答 1

1

我有一种感觉,你在测试时创造community {0}shell {1,2,3}就地。IE

NodeClusterSimilarity similarity( graph, {0}, {1,2,3} );

在这种情况下,您将获取临时右值的地址,这些地址在您调用getValue(). 你有两个选择:

  • community并且shell必须比您的NodeClusterSimilarity实例寿命更长。基本上在调用构造函数之前将它们作为单独的变量放在堆栈上。
  • 使成员成为const &,如果你不修改它们,它们应该绑定到右值并在生命周期内保持它们的生命周期Acceptability

具体来说第二点:

class Acceptability {
  public:
    Graph const& G;
    std::unordered_set<node> const& community;
    std::unordered_set<node> const& shell;
  public:
    Acceptability(Graph const& G, std::unordered_set<node> const& community,
                  std::unordered_set<node> const& shell);
    virtual ~Acceptability();
    virtual double getValue(node v) = 0;
};
于 2013-06-14T02:48:25.210 回答