Is there a way to check if its safe to copy or assign an object in C++?
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 c开发者_如何学Copy constructor, I'd do it in the obvious way, but I don't. How can I check it?
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.
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)
精彩评论