有没有办法检查在 C++ 中复制或分配对象是否安全?

发布于 2024-10-04 18:45:14 字数 691 浏览 0 评论 0原文

我有以下问题。我正在一个必须用 c++ 执行的程序中使用 C 库 igraph (http://igraph.sourceforge.net/)。所以我找到了这个 C 库的 C++ 包装器 (http://code.google.com/p/igraphhpp/),它在一个名为 Graph 的类中提供了一些我想使用的漂亮接口。

我的程序中有以下类:

class Agent 
{
private: 
  double beta;  
  Graph * innerGraph;
public:
  Agent(int N, double beta_) {
    innerGraph = new Graph;
    *innerGraph = Graph::full(N);
    beta = beta_;
  };
  ~Agent() {delete innerGraph;}
  void MCStep();
};

函数 MCStep() 必须执行以下操作:

  • 制作 *innerGraph 中包含的图形的副本,
  • 对此副本执行一些操作,而不更改原始副本,
  • 检查如果更改后的副本满足某些条件,如果是,则使用此新的修改后的图形更新 *innerGraph 。

如果我知道该库实现了安全复制构造函数,我会以明显的方式执行此操作,但我没有。我怎样才能检查它?

I have the following problem. I'm using the C library igraph (http://igraph.sourceforge.net/) in a program I must do in c++. So I found a c++ wrapper of this C library (http://code.google.com/p/igraphhpp/) that provides some nice interface I wanted to use, in a class called Graph.

I have the following class in my program:

class Agent 
{
private: 
  double beta;  
  Graph * innerGraph;
public:
  Agent(int N, double beta_) {
    innerGraph = new Graph;
    *innerGraph = Graph::full(N);
    beta = beta_;
  };
  ~Agent() {delete innerGraph;}
  void MCStep();
};

The function MCStep() must do the following:

  • make a copy of the Graph contained in *innerGraph,
  • do some stuff to this copy, without altering the original,
  • check if the altered copy satisfy some condition and, if yes, update *innerGraph with this new modified graph.

If I knew that the library implements a safe copy constructor, I'd do it in the obvious way, but I don't. How can I check it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吹泡泡o 2024-10-11 18:45:14

检查Graph的源码,看看复制构造函数是否调用了这个函数:

http:// igraph.sourceforge.net/doc/html/ch04s02s01.html#igraph_copy

没有通用的方法 - C++ 语言本身对“深拷贝”或“浅拷贝”一无所知,因此拷贝构造函数对其都是相同的就这一点而言。在理想的情况下,任何发布这样的 C++ 包装器的人都会对其进行记录,在这种情况下,可能应该将其制作为完整的深层副本。

Check the source of Graph, see whether the copy constructor calls this function:

http://igraph.sourceforge.net/doc/html/ch04s02s01.html#igraph_copy

There's no general way - the C++ language itself knows nothing about "deep copies" or "shallow copies", so copy constructors are all the same to it as far as that's concerned. In an ideal world, anyone publishing a C++ wrapper like this would document it, and in this case probably should make it a complete deep copy.

魂ガ小子 2024-10-11 18:45:14

由于您正在使用指向 Graph 的指针,难道您不能在步骤 3 中交换指针吗? (交换后不要忘记删除临时文件)

Since you're working with pointers to Graph, can't you just swap the pointers in step 3? (Don't forget to delete the temporary after swap)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文