Dom*_*nic 56 c++ pointers destructor memory-management copy-constructor
这是一个初学者的问题,但我很长一段时间没有做过C++,所以这里......
我有一个包含动态分配数组的类,比方说
class A
{
int* myArray;
A()
{
myArray = 0;
}
A(int size)
{
myArray = new int[size];
}
~A()
{
// Note that as per MikeB's helpful style critique, no need to check against 0.
delete [] myArray;
}
}
Run Code Online (Sandbox Code Playgroud)
但现在我想创建一个动态分配的这些类的数组.这是我目前的代码:
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
arrayOfAs[i] = A(3);
}
Run Code Online (Sandbox Code Playgroud)
但这种情况非常糟糕.因为在循环迭代完成时,A
(通过A(3)
调用)创建的新对象会被破坏for
,这意味着myArray
该A
实例的内部delete []
变为-ed.
所以我认为我的语法必定是非常错误的?我想有一些看起来像矫枉过正的修复,我希望避免:
A
.vector<int>
,vector<A>
所以我不必担心这一切.arrayOfAs
一个A
对象数组,而是一个A*
指针数组.我认为这只是一些初学者的事情,当尝试动态分配具有内部动态分配的事物数组时,实际上有一种语法.
(此外,风格评论也很受欢迎,因为自从我做C++以来已经有一段时间了.)
未来观众的更新:以下所有答案都非常有用.由于示例代码和有用的"4规则",Martin被接受了,但我真的建议全部阅读它们.有些是关于错误的好的,简洁的陈述,有些人正确指出了如何以及为什么vector
s是一个好的方法.
Mar*_*ork 121
对于构建容器,您显然希望使用其中一个标准容器(例如std :: vector).但是,当您的对象包含RAW指针时,这是您需要考虑的事情的完美示例.
如果你的对象有一个RAW指针,那么你需要记住3的规则(现在是C++ 11中的规则5).
这是因为如果没有定义,编译器将生成这些方法的自己版本(见下文).在处理RAW指针时,编译器生成的版本并不总是有用.
复制构造函数很难得到正确(如果你想提供强大的异常保证,这是非常重要的).可以根据复制构造函数定义赋值运算符,因为您可以在内部使用复制和交换习惯用法.
有关包含指向整数数组的指针的类的绝对最小值的详细信息,请参见下文.
知道让它变得正确是非常重要的,你应该考虑使用std :: vector而不是指向整数数组的指针.该向量易于使用(和扩展),并涵盖与异常相关的所有问题.将以下类与下面的A定义进行比较.
class A
{
std::vector<int> mArray;
public:
A(){}
A(size_t s) :mArray(s) {}
};
Run Code Online (Sandbox Code Playgroud)
看看你的问题:
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
// As you surmised the problem is on this line.
arrayOfAs[i] = A(3);
// What is happening:
// 1) A(3) Build your A object (fine)
// 2) A::operator=(A const&) is called to assign the value
// onto the result of the array access. Because you did
// not define this operator the compiler generated one is
// used.
}
Run Code Online (Sandbox Code Playgroud)
编译器生成的赋值运算符几乎适用于所有情况,但是当RAW指针处于运行状态时,您需要注意.在您的情况下,由于浅拷贝问题导致问题.您最终得到了两个包含指向同一块内存的指针的对象.当A(3)在循环结束时超出范围时,它会调用其指针上的delete [].因此,另一个对象(在数组中)现在包含一个指向已返回系统的内存的指针.
编译器生成了拷贝构造函数 ; 使用该成员复制构造函数复制每个成员变量.对于指针,这只意味着指针值从源对象复制到目标对象(因此是浅拷贝).
编译器生成赋值运算符 ; 使用该成员赋值运算符复制每个成员变量.对于指针,这只意味着指针值从源对象复制到目标对象(因此是浅拷贝).
所以包含指针的类的最小值:
class A
{
size_t mSize;
int* mArray;
public:
// Simple constructor/destructor are obvious.
A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
~A() {delete [] mArray;}
// Copy constructor needs more work
A(A const& copy)
{
mSize = copy.mSize;
mArray = new int[copy.mSize];
// Don't need to worry about copying integers.
// But if the object has a copy constructor then
// it would also need to worry about throws from the copy constructor.
std::copy(©.mArray[0],©.mArray[c.mSize],mArray);
}
// Define assignment operator in terms of the copy constructor
// Modified: There is a slight twist to the copy swap idiom, that you can
// Remove the manual copy made by passing the rhs by value thus
// providing an implicit copy generated by the compiler.
A& operator=(A rhs) // Pass by value (thus generating a copy)
{
rhs.swap(*this); // Now swap data with the copy.
// The rhs parameter will delete the array when it
// goes out of scope at the end of the function
return *this;
}
void swap(A& s) noexcept
{
using std::swap;
swap(this.mArray,s.mArray);
swap(this.mSize ,s.mSize);
}
// C++11
A(A&& src) noexcept
: mSize(0)
, mArray(NULL)
{
src.swap(*this);
}
A& operator=(A&& src) noexcept
{
src.swap(*this); // You are moving the state of the src object
// into this one. The state of the src object
// after the move must be valid but indeterminate.
//
// The easiest way to do this is to swap the states
// of the two objects.
//
// Note: Doing any operation on src after a move
// is risky (apart from destroy) until you put it
// into a specific state. Your object should have
// appropriate methods for this.
//
// Example: Assignment (operator = should work).
// std::vector() has clear() which sets
// a specific state without needing to
// know the current state.
return *this;
}
}
Run Code Online (Sandbox Code Playgroud)
IMi*_*Mil 10
我建议使用std :: vector:类似的东西
typedef std::vector<int> A;
typedef std::vector<A> AS;
Run Code Online (Sandbox Code Playgroud)
STL的轻微矫枉过正没有任何问题,您将能够花更多的时间来实现应用程序的特定功能,而不是重新发明自行车.
A对象的构造函数动态分配另一个对象,并在原始指针中存储指向该动态分配对象的指针.
对于该场景,您必须定义自己的复制构造函数,赋值运算符和析构函数.编译器生成的将无法正常工作.(这是"三巨头法则"的必然结果:任何析构函数,赋值运算符,复制构造函数的类通常都需要3).
你已经定义了自己的析构函数(并且你提到了创建一个复制构造函数),但你需要定义三个中的另外两个.
另一种方法是将指针存储到动态分配int[]
的其他对象中,这些对象将为您处理这些事情.像vector<int>
(如你所提到的)或a boost::shared_array<>
.
要将其降低 - 为了充分利用RAII,您应该尽可能避免处理原始指针.
而且由于你要求其他样式批评,一个小问题是,当你删除原始指针时,你不需要在调用之前检查0 delete
- delete
通过什么都不做来处理这种情况所以你不必用检查混乱你的代码.