简体   繁体   中英

vector and const

Consider this

 void f(vector<const T*>& p)
 {
 }
 int main()
 { 
  vector<T*> nonConstVec;
  f(nonConstVec);
 }

The following does not compile.The thing is that vector<T*> can not be converted to vector <const T*> , and that seems illogically to me , because there exists implicit conversion from T* to const T* . Why is this ?

vector<const T*> can not be converted to vector <T*> too, but that is expected because const T* can not be converted implicitly to T* .

I've added a few lines to your code. That's sufficient to make it clear why this is disallowed:

void f(vector<const T*>& p)
 {
    static const T ct;
    p.push_back(&ct); // adds a const T* to nonConstVec !
 }
 int main()
 { 
  vector<T*> nonConstVec;
  f(nonConstVec);
  nonConstVec.back()->nonConstFunction();
 }

vector<T> and vector<const T> are unrelated types. The fact that T can be converted to const T doesn't mean a thing here.

You have to think about it from a type system's standpoint. Instantiated vector<int> doesn't have anything in common with vector<const int> .

It may be worth showing why it's a breach of const-correctness to perform the conversion you want:

#include <vector>
const int a = 1;

void addConst(std::vector<const int *> &v) {
    v.push_back(&a); // this is OK, adding a const int* to a vector of same
}

int main() {
    std::vector<int *> w;
    int b = 2;
    w.push_back(&b);  // this is OK, adding an int* to a vector of same
    *(w.back()) = 3;  // this is OK, assigning through an int*
    addConst(w);      // you want this to be OK, but it isn't...
    *(w.back()) = 3;  // ...because it would make this const-unsafe.
}

The problem is that vector<int*>.push_back takes a pointer-to-non-const (which I'll call a "non-const pointer" from now on). That means, it might modify the pointee of its parameter. Specifically in the case of vector, it might hand the pointer back out to someone else who modifies it. So you can't pass a const pointer to the push_back function of w, and the conversion you want is unsafe even if the template system supported it (which it doesn't). The purpose of const-safety is to stop you passing a const pointer to a function which takes a non-const pointer, and this is how it does its job. C++ requires you to specifically say if you want to do something unsafe, so the conversion certainly can't be implicit. In fact, because of how templates work, it's not possible at all (see later).

I think C++ could in principle preserve const-safety by allowing a conversion from vector<T*>& to const vector<const T*>& , just as int ** to const int *const * is safe. But that's because of the way vector is defined: it wouldn't necessarily be const-safe for other templates.

Likewise, it could in theory allow an explicit conversion. And in fact, it does allow an explicit conversion, but only for objects, not references ;-)

std::vector<const int*> x(w.begin(), w.end()); // conversion

The reason it can't do it for references is because the template system can't support it. Another example that would be broken if the conversion were allowed:

template<typename T> 
struct Foo {
    void Bar(T &);
};

template<>
struct Foo<const int *> {
    void Baz(int *);
};

Now, Foo<int*> doesn't have a Baz function. How on earth could a pointer or reference to Foo<int*> be converted to a pointer or reference to Foo<const int*> ?

Foo<int *> f;
Foo<const int *> &g = f; // Not allowed, but suppose it was
int a;
g.Baz(&a); // Um. What happens? Calls Baz on the object f?

Think of like this:

You have two class like this:

class V  { T*       t;};
class VC { T const* t;};

Do you expect these two classes to be convertible automatically?
This is basically what a template class is. Each variation is a completely new type.

Thus vector<T*> and vector<T const*> are completely different types.

My first question is do you really want to store pointers?

If yes, I would suggest looking at boost::ptr_container. This holds pointers and deletes them when the vector is destroyed. But more importantly it treats the contained pointers as a normal std:vector treats its contained objects. Thus by making the vector const you can only access its members as const

void function(boost::ptr_vector<T> const& x)
{
     x.push_back(new T);  // Fail x is const.
     x[4].plop();         // Will only work if plop() is a const member method.
}

If you don't need to store pointers then store the objects (not the pointers) in the container.

void function(std::vector<T> const& x)
{
     x.push_back(T());    // Fail x is const.
     x[4].plop();         // Will only work if plop() is a const member method.
}

Others have already given the reason why the code you gave doesn't compile, but I have a different answer on how to deal with it. I don't believe there's any way to teach the compiler how to automatically convert the two (because that would involve changing the definition of std::vector ). The only way around this annoyance is to do an explicit conversion.

Converting to a completely different vector is unsatisfying (wastes memory and cycles for something that should be completely identical). I suggest the following:

#include <vector>
#include <iostream>

using namespace std;

typedef int T;

T a = 1;
T b = 2;

void f(vector<const T*>& p)
{
    for (vector<const T*>::const_iterator iter = p.begin(); iter != p.end(); ++iter) {
        cout << **iter << endl;
    }
}
vector<const T*>& constify(vector<T*>& v)
{
  // Compiler doesn't know how to automatically convert
  // std::vector<T*> to std::vector<T const*> because the way
  // the template system works means that in theory the two may
  // be specialised differently.  This is an explicit conversion.
  return reinterpret_cast<vector<const T*>&>(v);
}
int main()
{
  vector<T*> nonConstVec;
  nonConstVec.push_back(&a);
  nonConstVec.push_back(&b);
  f(constify(nonConstVec));
}

I'm using reinterpret_cast to declare that the two things are the same. You SHOULD feel dirty after using it, but if you put it in a function by itself with a comment for those following you, then have a wash and try to continue on your way with a good conscience, though you will always (rightly) have that nagging worry about someone pulling the ground out from under you.

As others have said, conversions aren't applied to the template parameters. Put another way,

vector<T>

...and:

vector<const T>

... are completely different types.

If you are trying to implement const-correctness in regard to f() not modifying the contents of the vector, this might be more along the lines of what you're looking for:

void f(vector<T>::const_iterator begin, vector<T>::const_iterator end)
{
  for( ; begin != end; ++begin )
  {
    // do something with *begin
  }
}

int main()
{
  vector<T> nonConstVec;
  f(nonConstVec.begin(), nonConstVec.end());
}

除了其他答案,还值得阅读C ++ FQA Lite,其中这个(以及许多其他C ++特性)是从一个关键的POV讨论的:http: //yosefk.com/c++fqa/const.html#fqa-18.1

这就是模板的工作方式 - 不对模板参数应用任何转换,因此两个向量的类型完全不同。

Templates are a bit strange that way. The fact that there's an implicit conversion from T to U doesn't mean that there's an implicit conversion from XXX to XXX. It can be made to happen, but it takes a fair amount of extra work in the template code to make it happen, and offhand, I doubt the techniques were all known when std::vector was being designed (more accurately, I'm pretty sure they weren't known).

Edit: Issues like this are part of the motivation behind using iterators. Even though a container of X isn't implicitly convertible to a container of const X , a container<X>::iterator is implicitly convertible to a container<X>::const_iterator .

If you replace your:

void f(vector<const T*>& p) {}

with:

template <class const_iter>
void f(const_iter b, const_iter e) {}

Then:

int main() { 
    vector<T*> nonConstVec;
    f(nonConstVec.begin(), nonConstVec.end());
    return 0;
}

will be just fine -- and so will:

vector<T const *> constVec;
f(constVec.begin(), constVec.end());

Both vector<const T*> and vector<T*> are completely different types. Even if you write const T* inside your main() , your code wont compile. You need to provide specialization inside main.

The following compiles:

 #include<vector>
 using namespace std;

 template<typename T>
 void f(vector<const T*>& p)
 {
 }
 int main()
 { 
     vector<const int*> nonConstVec;
     f(nonConstVec);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM