C++ 初始化和赋值的不同

博客提及赋值操作复杂,还列举了网摘、CtrlC、源代码搜索引擎、百家姓查询、唐诗宋词元曲查询等内容,重点围绕搜索引擎展开。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++中初始化和赋值操作差别是很大的。

对于基本数据类型差别不大:

比如:
int a = 12; // initialization, copy 0X000C to a
a = 12; // assignment, copy 0X000C to a

但是对用户自定义的数据类型比如String 初始化和赋值就差别很大:
class String {
public:
String( const char *init ); // intentionally not explicit!
~String();
String( const String &that );
String &operator =( const String &that );
String &operator =( const char *str );
void swap( String &that );
friend const String // concatenate
operator +( const String &, const String & );
friend bool operator <( const String &, const String & );
//...
private:
String( const char *, const char * ); // computational
char *s_;
};

初始化的构造过程比较简单:先分配一个足够大的空间然后填充上数据:

String::String( const char *init ) {
if( !init ) init = "";
s_ = new char[ strlen(init)+1 ];
strcpy( s_, init );
}

析构过程更简单:
String::~String() { delete [] s_; }

但是如果赋值操作就复杂多了:

String &String::operator =( const char *str ) {
if( !str ) str = "";
char *tmp = strcpy( new char[ strlen(str)+1 ], str );
delete [] s_;
s_ = tmp;
return *this;
}

看来在条件允许的情况下最好在初始化的时候就赋值,而尽量避免用=号赋值了。


相关链接: C++ Common Knowledge: Assignment and Initialization Are Different

其他
机器人聊天

网摘

近日心情

爱吧

CtrlC 源代码搜索引擎



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值