首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >赋值运算符与复制构造函数C++

赋值运算符与复制构造函数C++
EN

Stack Overflow用户
提问于 2013-09-24 05:19:11
回答 1查看 21.4K关注 0票数 20

我有以下代码来测试我对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确实存在,那么为什么不调用赋值操作符呢?

EN

回答 1

Stack Overflow用户

发布于 2013-09-24 05:33:51

想一想这个调用:

displayInteger( "intVal1", intVal1 );

您将在displayIntegerintObj参数中创建intVal1的副本

void displayInteger( char* str, Integer intObj )
{
  cout << str << " is " << intObj.getInteger() << endl;
}

该副本将指向与intVal1相同的int。当displayInteger返回时,intObj将被销毁,这将导致int被销毁,并且intVal1中的指针指向无效对象。在这一点上,如果您尝试访问该值,则所有的下注都将关闭(也称为未定义的行为)。类似的事情也发生在intVal2上。

在更一般的级别上,通过删除复制构造函数,您违反了三个规则,这通常会导致此类问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18969083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档