C ++奇怪的参数传递

时间:2013-06-14 01:08:44

标签: gcc c++11

当我给出参数时,我有一种奇怪的行为。我方法的标题是:

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) {
}

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

任何人都可以告诉我,出了什么问题?

1 个答案:

答案 0 :(得分:1)

我觉得您在测试时就地创建了community {0}shell {1,2,3}。即。

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

在这种情况下,您将获取临时右值的地址,这些地址在您拨打getValue()时被解除分配。您有两种选择:

  • communityshell必须比您的NodeClusterSimilarity实例更长久。在调用构造函数之前,基本上将它们作为堆栈上的单独变量。
  • 如果您没有修改成员,请将成员设为const &,并且他们应绑定到rvalues并在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;
};