为什么仅在原语的情况下才在函数返回类型中忽略类型限定符?

时间:2016-11-19 04:17:25

标签: c++

在尝试从c ++项目中删除警告时,我无法理解为什么第一个函数返回int会发出警告“警告:在函数返回类型上忽略类型限定符”但是返回std :: string的第二个函数不会发出此警告?

   //first function
    const int getX()
    {
        int x =9;
        return x;
    }
   //second function
    const std::string getTemp()
    {
        std::string test = "Test..";
        return test;
    }

1 个答案:

答案 0 :(得分:8)

基本类型上的

getX() = 5; // error, even if getX() returns a non-const int. 对返回值没有影响,因为您无法修改基本类型的右值。

std::string s = getTemp().append("extra");
   // error if getTemp() returns a `const std::string`, but valid
   // if getTemp() returns a non-const `std::string`.

对于类类型,const可以有所作为:

no ruby in PATH/CONFIG
 DEBUG [a202e059] 
 DEBUG [a202e059]       /home/takebackdemo/.rbenv/versions/2.1.0/bin/ruby /home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/bin/rake assets:precompile:all RAILS_ENV=developm
ent RAILS_GROUPS=assets
 DEBUG [a202e059] 
 DEBUG [a202e059]       rake aborted!
 DEBUG [a202e059]       Command failed with status (1): [/home/takebackdemo/.rbenv/versions/2.1.0/b...]
 DEBUG [a202e059]       /home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/gems/actionpack-3.2.13/lib/sprockets/assets.rake:12:in `ruby_rake_task'
/home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/gems/actionpack-3.2.13/lib/sprockets/assets.rake:21:in `invoke_or_reboot_rake_task'
/home/takebackdemo/apps/TakeBackDMS_development/shared/bundle/ruby/2.1.0/gems/actionpack-3.2.13/lib/sprockets/assets.rake:29:in `block (2 levels) in <top (required)>'
 DEBUG [a202e059]       Tasks: TOP => assets:precompile
 DEBUG [a202e059]       (See full trace by running task with --trace)
(Backtrace restricted to imported tasks)