Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I push a const pointer to std::vector?

Consider the piece of code:

class T;

void constructVector(const T* item)
{
   std::vector<T*> v;
   v.push_back(item);
}

I get an error with MSVC 2010 compiler:

error: C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'const T *' to 'T *&&' with [ _Ty=T * ] Conversion loses qualifiers

I can see this particular conversion is illegal, but I don't believe my code is semantically wrong. I also believe there's push_back(const T&) variant, why isn't that matched to my call?

like image 838
Violet Giraffe Avatar asked Dec 25 '22 20:12

Violet Giraffe


2 Answers

Because that's a vector of non-const pointers. It won't convert a const pointer to a non-const pointer. That would defeat the purpose of const.

I believe that the push_back(const T&) is not what you're looking for, because that makes the T object itself const, it does not change the type of T from (*) to (const *).

You could make the vector a vector of const pointers :

void constructVector(const T* item)
{
    std::vector<const T*> v;
    v.push_back(item);
 }

Or you could change your function to take a non-const pointer :

 void constructVector(T* item)
 {
    std::vector<T*> v;
    v.push_back(item);
 }
like image 168
apLundell Avatar answered Feb 07 '23 09:02

apLundell


Drop const

void constructVector( const T* item);

or

Use:

void constructVector(const T* item)
{
   std::vector<const T*> v;
   v.push_back(item);
}
like image 30
P0W Avatar answered Feb 07 '23 10:02

P0W