我们在定义类时,常常会显得很随意,这样会出现很多意想不到的错误,如下面的例子:
/**
*
*
*
*
*/
#include <stdio.h>
#include <iostream>
#include <deque>
#include <string.h>
class a
{
public:
a() : p(NULL)
{
p = new char[20];
char buf[] = "hello world!";
std::cout << buf << std::endl;
};
~a()
{
delete [] p;
p = NULL;
};
private:
char* p;
};
typedef std::deque<a> a_ptr_queue;
a_ptr_queue g_queue;
void func(const a& f)
{
g_queue.push_back(f);
}
int main()
{
a test;
func(test);
return 0;
}
这个例子有什么问题?
deque在析构元素a的时候将会崩溃,因为其p并未初始化即进行delete操作,这里有一点需要注意的是
deque在push_back(f)的时候是会对f进行浅拷贝的,无论f是不是引用。
这个地方已经遇到很多次了,还是会忘记,这个例子的教训是:
一:自定义类的时候不要太随意,尽量定义完整,包括拷贝,拷贝构造,=操作符,析构;
二:在使用STL时,对一些用法要掌握的更牢固;
正确的写法如下:
*
*
*
*
*/
#include <stdio.h>
#include <iostream>
#include <deque>
#include <string.h>
class a
{
public:
a() : p(new char[20])
{
char buf[] = "hello world!";
memcpy(p, buf, sizeof(buf));
};
a(const a& n) : p(new char[20])
{
memcpy(p, n.get_p(), 20);
}
char* get_p() const
{
return p;
}
~a()
{
delete [] p;
p = NULL;
};
private:
char* p;
};
typedef std::deque<a> a_ptr_queue;
a_ptr_queue g_queue;
void func(const a f)
{
g_queue.push_back(f);
}
int main()
{
a test;
func(test);
return 0;
}