template<typename T>
class mygreater
{
public:
bool operator()(T a,T b)
{
return a > b;
}
};
template<typename t>
class myless
{
public:
bool operator()(t a,t b)
{
return a < b;
}
};
template<typename T>
inline bool mygreater(T a, T b)
{
return a > b;
}
template<typename T>
inline bool myless(T a, T b)
{
return a < b;
}
template<typename T,typename Compare>
bool compare(T a,T b,Compare comp)
{
//通过函数指针调用函数,是没有办法内联的,效率低,因为有函数调用开销
return comp(a,b);//operator()(a,b)
}
把有operator()小括号运算符重载函数的对象,称作函数对象,或者称作仿函数。
Test(20) 显示生成临时对象 生存周期 :所在语句 C++编译对于对象构造的优化:用临时对象生成新对象的时候,临时对象就不产生了,直接构造新对象就是可以了。 Test t4(20); == Test t4 = Test(20); //显示生成临时对象 t4 = Test(30); t4 = (Test)30; //隐式生成临时对象 t4 = 30; Test *p = &Test(20); //p指向的是一个已经析构的临时对象 const Test &ref = Test(30);
Test t1(10,10); //1.Test(int,int)
int main()
{
Test t2(20,20); //3.Test(int,int)
Test t3 = t2; //4.Test(const Test&)
static Test t4 = Test(30,30); //5.Test(int,int)
t2 = Test(20,30); //6.Test(int,int) operator= ~Test()
t2 = (Test)(30,30);//7.Test(int,int) operator= ~Test()
t2 = 6; //8.Test(int,int) operator=~Test()
Test* p1 = new Test(30,3); //9.Test(int,int)
Test* p2 = new Test[2]; //10.Test(int,int) Test(int,int)
Test* p3 = &Test(60,60); //11.Test(int,int) ~Test()
const Test &p4 = Test(30,30); //12.Test(int,int)
delete p1; //13~Test()
delete []p2; //14.~Test() ~Test()
return 0;
}
Test t5(100,1000); //2.Test(int,int)
//注意:5,4,1最后析构
Test function(Test t) //3.Test(const Test&)
{
int val = t.getDaa();
Test tmp(val); //4.Test(int)
return tmp; //5.Test(const Test&) 在主函数中构造一个临时函数对象
//6.~Test()
//7.~Test()
}
int main()
{
Test t1; //1.Test(int)
Test t2;//2.Test(int)
t2 = function(t1);
//函数调用,实参到形参,是初始化,不是赋值
//8. operator =
//9.~Test() 析构5.的临时对象
//10.~Test()析构2.对象
//11.~Test()析构1.对象
return 0;
}
Test function(Test &t)
{
int val = t.getDaa();
Test tmp(val); //3.Test(int)
return tmp; //4.Test(const Test&) 在主函数中构造一个临时函数对象
//5.~Test()
}
int main()
{
Test t1; //1.Test(int)
Test t2;//2.Test(int)
t2 = function(t1);
//函数调用,实参到形参,是初始化,不是赋值
//6. operator =
//7.~Test() 析构4.的临时对象
//8.~Test()析构2.对象
//9.~Test()析构1.对象
return 0;
}
Test function(Test &t)
{
int val = t.getDaa();
return Test(val); //在主函数中直接构造一个函数对象(用临时对象构造一个新对象)
//3.Test(int)不会先进行拷贝构造,
}
int main()
{
Test t1; //1.Test(int)
Test t2;//2.Test(int)
t2 = function(t1);
//4. operator =
//5.~Test() 析构3.的临时对象
//6.~Test()析构2.对象
//7.~Test()析构1.对象
return 0;
}
Test function(Test &t)
{
int val = t.getDaa();
return Test(val);
//2.Test(int) 直接构造t2
}
int main()
{
Test t1; //1.Test(int)
Test t2 = function(t1);//又是临时对象拷贝构造同类型的新对象t2
//3.~Test()析构2.对象
//4.~Test()析构1.对象
return 0;
}
std::vector<int> source = {1, 2, 3, 4, 5};
std::vector<int> destination = std::move(source); // 移动 source 到 destination
template<typename T>
void process(T&& arg) {
another_function(std::forward<T>(arg)); // 保持参数 arg 的原始类型(左值引用或右值引用)
}