我的部分任务是创建一个类,其中包含两个其他两个类的列表并创建“The big 4”(构造函数,复制构造函数,operator =,析构函数)
这就是我的所作所为:
using namespace std;
class A{...};
class B{...};
class C{
list<A> a;
list<B> b;
public:
C();
~C();
C(const C& c);
void operator=(const C& c);
};
C::C(){
//How to allocate memory for a and b?
}
C::~C(){
//How to free the memory?
}
C::C(const C& c){
a=c.a;
b=c.b;
}
void operator=(const C& c){
if(&c==this) return;
// how do I delete a and b?
a=c.a;
b=c.b;
}
你能清除我不理解的东西(作为代码中的评论)。如果我没有做任何正确的事情,还要提供建议吗?
答案 0 :(得分:2)
由于您使用的是值(std::list
值),因此无需执行任何操作。您的构造函数将自动调用std::list
构造函数,从而分配所需的任何资源。析构函数将调用std::list
析构函数,从而释放它获取的资源。
如果您持有指向列表(即std::list<A> *a;
)或指针列表(std::list<A*> a;'
)或两者({{1}的指针),那么 需要一些额外的工作})。
答案 1 :(得分:0)
//如何为a和b分配内存?
您不需要自己分配内存。因为你在堆栈上分配你的成员变量。当有人实现你的课程时会自动设置。
//如何释放记忆?
你不需要自己释放记忆。出于同样的原因。当scop结束时,你的堆栈变量将自动解除分配。
//如何删除a和b?
为什么需要删除a和b?您正在将其他对象的数据复制到此。
答案 2 :(得分:0)
您的变量正在使用不需要显式删除的自动存储类。
您的作业运算符
void operator=(const& C rhs);
不应该返回无效。 //因为这不是内置类型所做的,并且阻止了赋值链接。
e.g。
int x, y, z;
x = y = z = 0;
看起来你试图用你的评论实现移动语义
// how do I delete a and b?
您的赋值运算符应该复制状态,或者您应该记录它使用非标准行为。例如移动语义,boost :: noncopyable等等。
答案 3 :(得分:0)
如果你使用std :: list,你的A或B类应该: 1可以在堆栈和堆上分配 2不能是单身对象。
答案 4 :(得分:0)
随着移动构造函数的出现,它现在成为了六巨头。学习并了解这里的所有细节,你将获得班级锅炉板的硕士学位。
#include <list>
class A {};
class B {};
class C{
std::list<A> a;
std::list<B> b;
public:
typedef std::list<A>::size_type size_type;
explicit C(size_type sz =0);
virtual ~C();
C(const C& c);
// Specialize external swap. Necessary for assignment operator below,
// and for ADL (argument-dependant lookup).
friend void swap(C& first, C& second);
// Assignment-operator. Note that the argument "other" is passed by value.
// This is the copy-and-swap idiom (best practice).
C& operator=(C other); // NOTE WELL. Passed by value
// move-constructor - construct-and-swap idiom (best practice)
C(C&& other);
};
C::C(size_type sz) : a(sz), b(sz) {}
C::~C(){}
C::C(const C& c) :a(c.a), b(c.b){}
void swap(C& first, C& second) {
// enable ADL (best practice)
using std::swap;
swap(first.a, second.a);
swap(first.b, second.b);
}
// Assignment-operator. Note that the argument "other" is passed by value.
// This is the copy-and-swap idiom (best practice).
C& C::operator=(C other) {
swap(*this, other); // Uses specialized swap above.
return *this;
}
// move-constructor - construct-and-swap idiom (best practice)
C::C(C&& other): a(0) , b(0) {
swap(*this, other);
}