سؤال

For whatever reason, I ended up with code that looked like this

typedef std::vector<double> Vector;
void f(Vector const& v) {
  Vector const* p;
  p = &v;
}

This throws a bad_alloc exception at the point of assignment. Why? Does it matter that f was called on a non-cast vector? This is C++03 compiled on gcc 4.1.

** Edit ** This is inside some code running inside google mock that I see the exception. I tried to tear the code out and compile it separately and it worked fine. Looking further

** Further Edit ** So the problem was actually that the assignment happened in the last line of a constructor of an object that was itself a member of another object. The next object in the initializer list of the parent object was where the exception was coming from, but gdb made it look like it was happening on the last line of the previous object's constructor where this assignment was taking place. Thanks for all the downvotes to remind me how misguided the question was.

هل كانت مفيدة؟

المحلول

There is no possible way that code can raise a std::bad_alloc exception (or any other exception, for that matter), since all you are doing is assigning a pointer value to a pointer variable. std::bad_alloc is raised by the new and new[] operators when a memory allocation fails, and there is no such memory allocation being performed in this code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top