1

我有一个关于良好 C++ 风格的问题:我想编写一个类“MyClass”,它有一个或一些指针作为成员,并且 MyClass 能够为这些指针分配内存。我想使用隐式给出默认复制构造函数(以及默认赋值操作符)来复制 MyClass 的一个实例,以便只复制指针并且新对象共享初始对象具有的数据分配。

我的想法是禁止复制对象(使用复制构造函数或赋值运算符创建)释放内存(以及为成员指针分配内存)。为了区分复制的对象和原始对象(由构造函数创建),我想使用以下代码:

class MyClass
{
public:
       MyClass(): originalPtr(this) { data = new char[100000]; }
       ~MyClass() { if(originalPtr == this) delete[] data; }
private:
       MyClass *originalPtr;
       char *data; // shared data (not copiable)
       char otherFeatures[10]; // individual data (copiable)
};

这个解决方案(使用与this-pointer 的比较)会是一个好的风格(例如通过按值调用解析对象)还是有风险?当然,我假设原始对象的寿命总是比复制的对象长。

谢谢!

4

2 回答 2

1

No, this is a bad idea. If the pointers are shared by several instances, than the one to deallocate should be the last one to die, not the original one. This differs in the sense that the original one might not be the one to die, which would cause all others to be pointing at garbage. Even though you assume that it's the last one to die, you need to realise that the inner workings of a class should not rely on external assumptions. That is, the class has no guarantees on how its life span is managed by the rest of the implementation, so it shouldn't make assumptions.

In this situation you should track references to your data. The basic idea is to keep track of how many copies of the class you have. As soon as that count reaches zero, you are free to release that memory; the last copy has just died. Fortunately for you, STL already provides such an implementation. These are known as Smart Pointers. There are others, such as std::unique_ptr, which makes the opposite by ensuring that the data is owned only by a single instance.

于 2015-07-21T10:27:59.427 回答
0

好的,假设一般情况下,原始对象最终没有死。我喜欢只计算实例的想法。例如,可以使用这样一个概念:

class MyClass
{
public:
   MyClass(): countOfInstances(new int())
   {
       ++*countOfInstances;
       data = new char[100000];
   }

   ~MyClass()
   {
       --*countOfInstances;
       if(!countOfInstances)
       {
           delete[] data;
           delete countOfInstances;
       }
   }    

   MyClass(const MyClass &other) // analogous for the assignment operator
   {
       countOfInstances = other.countOfInstances;
       data = other.data;
       otherFeatures = other.otherFeatures;
       ++*countOfInstances;
   }

private:
   int *countOfInstances;
   char *data; // shared data (not copiable)
   char otherFeatures; // individual data (copiable)

};

在这里,还应确保在允许复制之前完全分配共享内存。

于 2015-07-21T11:11:55.443 回答