1.自动类型推导
auto,可以自行将定义的变量赋值为整形、浮点型、字符型.....
2.智能指针
c++11提供了三种类型的智能指针:std::unique_ptr、std::shared_ptr和std::weak_ptr。
在同一个程序中将某个资源使用智能共享指针进行管理,那么该数据无论在多少个函数内进行传递,都不会发生资源的复制,运行效率会大大提高。当所有的程序使用完毕后,还会自动收回,不会造成内存泄漏。
#include "iostream"
#include <memory>
int main()
{
auto p1 = std::make_shared<std::string>("This is a str.");// std::make_shared<数据类型/类>(参数);返回值,对应类的共享指针 std::shared_ptr<std::string> 写成 auto
std::cout<<"p1的引用计数:"<<p1.use_count()<<",指向内存地址:"<<p1.get()<<std::endl;//1
auto p2 = p1;
std::cout<<"p1的引用计数:"<<p1.use_count()<<",指向内存地址:"<<p1.get()<<std::endl;//2
std::cout<<"p2的引用计数:"<<p2.use_count()<<",指向内存地址:"<<p2.get()<<std::endl;//2
p1.reset();//释放引用,不指向"This is a str."所在内存ss
std::cout<<"p1的引用计数:"<<p1.use_count()<<",指向内存地址:"<<p1.get()<<std::endl;//0
std::cout<<"p2的引用计数:"<<p2.use_count()<<",指向内存地址:"<<p2.get()<<std::endl;//1 = 2-1
std::cout<<"p2的指向内存地址数据:"<<p2->c_str()<<std::endl;//调用成员方法"This is a str."
return 0;
}
3.Lambda表达式
#include "iostream"
#include "algorithm"
int main()
{
auto add = [](int a,int b) -> int { return a+b; };
int sum = add(200,50);
auto print_sum = [sum]() -> void
{
std::cout<<sum<<std::endl;
};
print_sum();
return 0;
}
首先定义了一个两数相加的函数,捕获列表为空,int a,int b是其参数,返回值类型是int,函数体是return a+b;接着调用add计算3+5并存储在sum中;然后又定义了一个函数print_sum,此时捕获列表中传入了sum;最后在函数体中输出sum的值。
4.函数包装器std::function
std::function是c++11引入的一种通用函数包装器,它可以存储任意可调用对象(函数、函数指针、Lambda表达式等)并提供统一的调用接口。
#include "iostream"
#include "functional"//函数包装器头文件
//自由函数
void save_with_free_fun(const std::string & file_name)
{
std::cout<<"自由函数:"<<file_name<<std::endl;
}
//成员函数
class FileSave
{
private:
/*data*/
public:
FileSave(/*args*/)= default;
~FileSave() = default;
void save_with_member_fun(const std::string & file_name)
{
std::cout<<"成员方法:"<<file_name<<std::endl;
};
};
int main()
{
FileSave file_save;
//Lambda函数
auto save_with_lambda_fun = [](const std::string & file_name) -> void
{
std::cout<<"Lambda函数:"<<file_name<<std::endl;
};
//save_with_free_fun("file_lwx.txt");
//file_save.save_with_member_fun("file_lvvx.txt");
//save_with_lambda_fun("file_25.txt");
std::function<void(const std::string &)> save1 = save_with_free_fun;
std::function<void(const std::string &)> save2 = save_with_lambda_fun;
//成员函数,放入包装器
std::function<void(const std::string &)> save3 = std::bind(&FileSave::save_with_member_fun,&file_save,std::placeholders::_1);
save1("file_lwx.txt");
save2("file_25.txt");
save3("file_lvvx.txt");
return 0;
}
!!!注意std::bind的使用方法