我有以下代码来测试我对C++中基本指针的理解:
// Integer.cpp
#include "Integer.h"
Integer::Integer()
{
value = new int;
*value = 0;
}
Integer::Integer( int intVal )
{
value = new int;
*value = intVal;
}
Integer::~Integer()
{
delete value;
}
Integer::Integer(const Integer &rhInt)
{
value = new int;
*value = *rhInt.value;
}
int Integer::getInteger() const
{
return *value;
}
void Integer::setInteger( int newInteger )
{
*value = newInteger;
}
Integer& Integer::operator=( const Integer& rhInt )
{
*value = *rhInt.value;
return *this;
}
// IntegerTest.cpp
#include <iostream>
#include <cstdlib>
#include "Integer.h"
using namespace std;
void displayInteger( char* str, Integer intObj )
{
cout << str << " is " << intObj.getInteger() << endl;
}
int main( int argc, char* argv[] )
{
Integer intVal1;
Integer intVal2(10);
displayInteger( "intVal1", intVal1 );
displayInteger( "intVal2", intVal2 );
intVal1 = intVal2;
displayInteger( "intVal1", intVal1 );
return EXIT_SUCCESS;
}
这段代码完全按照预期工作,它打印出来:
intVal1 is 0
intVal2 is 10
intVal1 is 10
但是,如果我删除复制构造函数,它会打印出类似如下的内容:
intVal1 is 0
intVal2 is 10
intVal1 is 6705152
我不明白为什么会这样。我的理解是,当赋值给一个不存在的对象时,会使用复制构造函数。这里intVal1
确实存在,那么为什么不调用赋值操作符呢?
发布于 2013-09-24 05:33:51
想一想这个调用:
displayInteger( "intVal1", intVal1 );
您将在displayInteger
的intObj
参数中创建intVal1
的副本
void displayInteger( char* str, Integer intObj )
{
cout << str << " is " << intObj.getInteger() << endl;
}
该副本将指向与intVal1
相同的int
。当displayInteger
返回时,intObj
将被销毁,这将导致int
被销毁,并且intVal1
中的指针指向无效对象。在这一点上,如果您尝试访问该值,则所有的下注都将关闭(也称为未定义的行为)。类似的事情也发生在intVal2
上。
在更一般的级别上,通过删除复制构造函数,您违反了三个规则,这通常会导致此类问题。
https://stackoverflow.com/questions/18969083
复制相似问题