为什么我不能将一个const指针推入std :: vector?

4

考虑以下代码:

class T;

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

我使用MSVC 2010编译器时出现了错误:
错误:C2664:'void std :: vector<_Ty> :: push_back(_Ty &&)':无法将参数1从'const T *'转换为'T *&&',其中[_Ty = T *]。转换失去了限定符
我可以看到这种特定的转换是非法的,但我不认为我的代码在语义上有错。我也相信有一个'push_back(const T&)'变量,那么为什么它没有与我的调用匹配?

1
你有一个非const项的向量,并尝试添加一个const项,系统提示它们不是同一类型。 - Jay
@Jay:哦,我知道你的意思了!愚蠢的问题。 - Violet Giraffe
2个回答

10
因为这是一个非const指针的向量。它不会将const指针转换为非const指针。这会使const的目的失去意义。
我认为push_back(const T&)不是您要寻找的,因为它会使T对象本身成为const,而不是将T的类型从(*)更改为(const *)。
您可以将向量设置为const指针的向量:
void constructVector(const T* item)
{
    std::vector<const T*> v;
    v.push_back(item);
 }

或者你可以将函数改为接受非const指针:

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

1

去掉 const

void constructVector(T* item);

或者

使用:

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

很明显const是这里的阻碍,直到Jay的评论我才明白为什么。 - Violet Giraffe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接