c++ auto

c++ auto,第1张

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仅仅是类型的替代,相关的其他限制,需要自身保证。 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5115616.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存