当我给出参数时,我有一种奇怪的行为。我方法的标题是:
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}
创建了shell {1,2,3}
类型的对象。然后我调用方法getValue()
,惊喜是:
传递参数后community
的大小为1
(hurraaaaaaas !!!)
但shell
的大小为0
:(([预期值显然为3
]
任何人都可以告诉我,出了什么问题?
答案 0 :(得分:1)
我觉得您在测试时就地创建了community {0}
和shell {1,2,3}
。即。
NodeClusterSimilarity similarity( graph, {0}, {1,2,3} );
在这种情况下,您将获取临时右值的地址,这些地址在您拨打getValue()
时被解除分配。您有两种选择:
community
和shell
必须比您的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;
};