《c++ primer 4th》--ch13--复制控制

vc8下的代码:

#include "stdafx.h"
#include <string>
using namespace std;

class A
{
public:
A(const string& s){;}
private:
A(const A& a){

}
};

int _tmain(int argc, _TCHAR* argv[])
{
A a="";
return 0;
}

这段代码按照书本上的理论应该是不能够通过编译的,但事实却通过了。
换到gcc之后,必须经过这样的修改

#include <string>
using namespace std;

class A{
public:
A(const char * cp){
}
// A(const string &s){};
A(const A &a){
};
};

int main(){
A a="";
return 0;
}


注:
1,class-type conversion(类类新转换)问题:char[] 到 string 不是C++中定义的标准转换,所以gcc在编译(A a="";)时报错,只有定义了精确匹配的A(const char * cp);gcc才得以编译通过
2,copy constructor(拷贝构造函数)问题:
[code]
private:
A(const A& a){};
[/code]
但是这段代码在g++报错,因为A a="";使用了copy initialization,所以copy constructor必须是public的
由此看来在学习c++的过程中,使用更符合标准gcc可能会增进对书本讲授知识的理解
3,运行结果,无论是vc8还是gcc4,都将调用copy constructor的过程优化掉了(某种意义上说vc8优化的更彻底,连加了private都不管),gcc虽然要求能够访问copy ctor,但就算加了-O0这个编译选项,编译出的东西也不会实际去调用copy ctor

在vc8下面测试绑定到引用

class A
{
public:
A(const string& s){}
};
int _tmain(int argc, _TCHAR* argv[])
{
const A a1 = "test"; //OK!
//const A& a2 = "test"; //cannot convert from 'const char [5]' to 'const A &'
}

对于const A& a2= "test";根据C++.Standard.2nd 8.5.3.5 最后一段的说明:
“Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy initialization (8.5)”
这个时候需要发生这样的操作 A temporary = "test";然后将a2绑定到这个临时对象。但是前面一步没有完成,说明vc8对标准做的扩展不完备,vc8将const char[]自动转换成const string& 只适用与普通的初始化。
因此,编写符合标准的C++代码是最优的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值