4

I have array of pointers:

private:
    LimitOrder* orders[Size];

In constructor i'm trying to fill it with NULL:

InternalIdAssigner::InternalIdAssigner(void):
    lastCleanId(0)
{
    std::fill(orders, orders + Size, NULL);

But this doesn't work, I receive error: error C2440: '=' : cannot convert from 'const int' to 'LimitOrder *'

What is the right way to fill array field with NULL?

2
  • 3
    If you're using a C++03x or later compliant toolchain, just add orders() to your initializer list. Commented May 19, 2014 at 4:14
  • An std::for_each would suffice. Even better than that, use a smart pointer. They get set to nullptr in their constructor. Commented May 19, 2014 at 4:14

3 Answers 3

7

The error message is kind of clear, if you understand what NULL really is: a literal 0.

When you pass 0 to a template, the deduced type is int, not a pointer type. While a literal 0 is implicitly convertible to any pointer type and will be a null pointer, after it if passed to fill it is just an int with value 0, which is not convertible to a pointer type.

In C++11 you could and should use nullptr instead of NULL. In C++03 you can also convert the pointer to the destination type:

std::fill(orders, orders + Size, static_cast<LimitOrder*>(0));

But then again, why go through the process in the first place when you can zero-initialize the array in the initializer list?

InternalIdAssigner::InternalIdAssigner()
   : lastCleanId(), orders() {}
Sign up to request clarification or add additional context in comments.

1 Comment

the last doesn't work in Visual Studio 2012, but probably works in more modern compiler
4

If you're using C++11:

std::fill(orders, orders + Size, nullptr);

otherwise:

std::fill(orders, orders + Size, static_cast<LimitOrder*>(NULL));

Or if you don't want to use a cast:

LimitOrder* tmp = NULL;
std::fill(orders, orders + Size, tmp);

Comments

3

My suggestion:

Change

std::fill(orders, orders + Size, NULL);

to

std::fill(orders, orders + Size, (LimitOrder*)NULL);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.