栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ auto

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ auto

实际上,写了很长时间的c++,其中c++11中引入的auto是很有用的,但是,之前遇到问auto是否能够保证const和reference(&)的属性时,一时不知道如何回答,所以写一小段程序验证一下结论: auto不能保证掐前面所述的属性, 测试代码如下:

#include 
#include 

using namespace std;

class Test
{
public:
    Test()
    {

    }

public:
    const std::string& getString()
    {
        return str;
    }

public:
    std::string str;
};

int main()
{
    Test test;
    test.str = "abc";
    std::cout << "test.str address = " << (unsigned long long int)(&test.str) << ", value = " << test.str << std::endl;

    auto auto_str = test.getString();
    std::cout << "A auto_str address = " << (unsigned long long int)(&auto_str) << ", value = " << auto_str << std::endl;
    auto_str += "efg";
    std::cout << "B auto_str address = " << (unsigned long long int)(&auto_str) << ", value = " << auto_str << std::endl;

    const std::string& ref_str = test.getString();
    std::cout << "ref_str = " << (unsigned long long int)(&(ref_str)) << ", value = " << ref_str << std::endl;

    return 0;
}

代码运行结果如下:  说明auto仅仅是类型的替代,相关的其他限制,需要自身保证。 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433489.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号