vendredi 21 août 2015

Type of an object returned by const value

While answering to this question, I've figured out something that seems odd to me. Look at this code:

#include <vector>

// return a vector by const value
const std::vector<double> build_up()
{
    std::vector<double> ret;
    ret.push_back(1.0);
    return ret;
}

int main()
{
    auto v = build_up();
    // successfully compiles, but shouldn't be v const???
    v.push_back(2);
}

Inside the main function, the type of the object returned by the function build_up is deduced by auto as a non-const std::vector<double>.

  • why auto take away the const qualifier?
  • is it just a matter of auto type deduction, or the type of the returned object is actually non-const?

Aucun commentaire:

Enregistrer un commentaire