C++复制初始化与直接初始化解决方法

C++复制初始化与直接初始化
最近在学习C++Primer第四版一书,看到复制初始化与直接初始化一节,其中书中说对类类型使用复制初始化总是调用类的复制构造函数,所以抄了一段测试代码研究,代码如下:

class SmallInt
{
public:
SmallInt(int i = 0) : val(i)
{
std::cout << "SmallInt::SmallInt(int i = 0)" << std::endl;
if (i < 0 || i > 255)
{
throw std::out_of_range("Bad SmallInt initializer");
}
}
SmallInt(const std::string& s) : str(s) 
{
std::cout << "SmallInt::SmallInt(const string& s)" << std::endl;

}
SmallInt(const SmallInt& s) : val(s.val), str(s.str)
{
std::cout << "SmallInt::SmallInt(const SmallInt& s)" << std::endl;
}
private:
unsigned int val;
std::string str;
};

int main()
{
SmallInt si = 3.14;
SmallInt bi = std::string("aa");
return 0;
}

执行结果如下:
SmallInt::SmallInt(int i = 0)
SmallInt::SmallInt(const string& s)
从结果中可以看出没有调用复制构造函数,是不是编译器对代码进行了优化,直接调用了相应版本的构造函数,还是其他原因呢?
C++ 复制初始化 直接初始化

------解决方案--------------------
1) 一个对象作为函数参数,以值传递的方式传入函数体;
2) 一个对象作为函数返回值,以值传递的方式从函数返回;
3) 一个对象用于给另外一个对象进行初始化(常称为复制初始化);

#include <string>
#include <iostream>
using namespace std;
class SmallInt
{
public:
SmallInt(int i = 0) : val(i)
{
std::cout << "SmallInt::SmallInt(int i = 0)" << std::endl;
if (i < 0 
------解决方案--------------------
 i > 255)
{
throw std::out_of_range("Bad SmallInt initializer");
}
}
SmallInt(const std::string& s) : str(s) 
{
std::cout << "SmallInt::SmallInt(const string& s)" << std::endl;
}
SmallInt(const SmallInt& s) : val(s.val), str(s.str)
{
std::cout << "SmallInt::SmallInt(const SmallInt& s)" << std::endl;
}
public:
void   Func(SmallInt s){}
SmallInt   Func(){return *this;}
private:
unsigned int val;
std::string str;
};

int main()
{
SmallInt si = 3.14;
SmallInt bi = std::string("aa");
SmallInt ai = bi; //调用拷贝构造
ai.Func(bi);//调用拷贝构造
ai.Func();//调用拷贝构造
return 0;
}