ROS2——C++新特性

1.自动类型推导

auto,可以自行将定义的变量赋值为整形、浮点型、字符型.....

2.智能指针

c++11提供了三种类型的智能指针:std::unique_ptr、std::shared_ptr和std::weak_ptr。

在同一个程序中将某个资源使用智能共享指针进行管理,那么该数据无论在多少个函数内进行传递,都不会发生资源的复制,运行效率会大大提高。当所有的程序使用完毕后,还会自动收回,不会造成内存泄漏。

#include "iostream"
#include 

int main()
{
    auto p1 = std::make_shared("This is a str.");// std::make_shared<数据类型/类>(参数);返回值,对应类的共享指针 std::shared_ptr 写成 auto
    std::cout<<"p1的引用计数:"<c_str()<
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<

首先定义了一个两数相加的函数,捕获列表为空,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<<"自由函数:"< void 
    {
        std::cout<<"Lambda函数:"< save1 = save_with_free_fun;
    std::function save2 = save_with_lambda_fun;
    //成员函数,放入包装器
    std::function 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的使用方法

你可能感兴趣的:(ROS2,c++,开发语言,ROS2)