`
xiongx
  • 浏览: 13442 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

《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(拷贝构造函数)问题:
private:
	A(const A& a){};

但是这段代码在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++代码是最优的选择。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics