我很好奇为什么复制构造函数对于我自己定义的类的动态分配如此重要。
我正在用动态分配实现低级c-string类,下面是我的类的快速视图。
class String
{
private:
char * buf;
bool inBounds( int i )
{
return i >= 0 && i < strlen(buf);
}
static int strlen(const char *src)
{
int count = 0;
while (*(src+count))
假设我创建了一个自定义的Array类,并具有以下构造函数:
Array::Array(size_t size)
{
mySize = size;
//myData is of type int*
myData = new int[mySize]; // this stuff is allocated on a heap
}
据我所知,本例中的默认复制构造函数将实现为:
Array::Array(Array& a)
{
mySize = a.mySize;
myData = a.myDat
在将指针的引用赋值给变量时,我遇到了一些奇怪的问题:本地代码工作正常,但它会在其他地方导致内存访问错误:
//This works fine
Gridcell* g = model.gc;
cout << g->LC_updated << " " << g << endl;
//When I include this, the program crashes elsewhere
//But output from this line is OK
Gridcell gc = *g;
cout << "Va
我在看新运算符的签名。这就是:
void* operator new (std::size_t size) throw (std::bad_alloc);
但是当我们使用这个运算符时,我们从不使用强制转换。i.e
int *arr = new int;
那么,在这种情况下,C++如何将void*类型的指针转换为int*呢?因为,即使是malloc也会返回一个void*,而我们需要显式地使用强制转换。
当我使用包含分配内存的B类向量时,会出现双空闲错误。
class B
{
public:
std::string a;
std::string b;
int *hehe;
B()
{
a = "Hello";
b = ", World!";
hehe = new int[7];
for (int i = 0; i < 7; ++i) {
hehe[i] = i;
}
}
~B() {
我收到运行时错误
malloc: *** error for object 0x10070c5c0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
使用以下堆栈跟踪:
这告诉我,析构函数~Clustering和~NodeMap (第一个是一个空存根,第二个是delete[])出了问题,但“被释放的指针”却没有。我怎么才能知道这件事呢?
另外,malloc_error_break在哪里?
复制构造函数用于很多事情,例如当我需要使用指针或为对象动态分配内存时。但是在tutorialpoint.com上看这个例子
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destr
Exceptional C++提到了以下代码
template <class T> class Stack
{
public:
Stack();
~Stack();
/*...*/
private:
T* v_; // ptr to a memory area big
size_t vsize_; // enough for 'vsize_' T's
size_t vused_; // # of T's actually in
将一个指针逐个复制到C++中的另一个元素,并获取"Error in `./hsc.exe':double free or corruption (!prev):0x0000000000aadcc0 * Aborted (core dumped)“。
我试着调试它,但我被“临时棒;”这行卡住了,因为我不能删除棒,因为我也在删除与"delete[]“相关的信息。
以下是代码的以下部分。
int * rods; // Defining rods and temp
int * temp;
int N_r =5;
rods = new int[N_r];
temp = new
假设我们有一个带有构造函数的类:
class MyClass
{
public:
MyClass()
{
//our code goes here
throw "OMG";//well, some code that throws an exception
}
};
现在,当出现异常时,正在执行堆栈展开。我还知道,如果从构造函数抛出异常,则不会调用相应对象的析构函数,因为对象一开始从未完全“创建”过。
我被这事弄糊涂了。对我来说,这意味着只有当构造函数完成时,对象才被视为“创建”。但是很明显,所有内存都是在调用构造函数之前(或之后)在某个