2

I am new to boost and I came across the boost pointer.

float *value = new float[9]; 
value[0] = 5; ...

The above is my initial c++ code.

I converted the above to boost shared pointer

boost::shared_ptr<float> value (new float);

But when I try to add to value it gives me error that i cant use operator[].

I guess this is too basic, but can I get some info on how to add values to memory pointed by the boost pointer.

4
  • @iharob Why luckily? Commented Apr 23, 2015 at 10:55
  • Boost ugly? It's one of the most respected C++ libraries there is. Many things from Boost find their way into the standard (e.g. shared_ptr) such is the level of authority is has on the C++ community. The Spirit EBNF grammar parsing library is simply brilliant. Commented Apr 23, 2015 at 11:02
  • This is bad for two reasons. C++ now has a standard shared point, std::shared_ptr so you should use that rather than boosts offering. Further, unless you have a significant reason otherwise, you should std::vector or std::array for 'array like' things. Commented Apr 23, 2015 at 11:02
  • @Bathsheba: That's an appeal to authority. Boost has just as much crap as anywhere else- sometimes more. And finding your way into the Standard is no mark of quality- see std::async, std::future, std::thread, std::vector<bool>, u8 literals, and so many more. Commented Apr 23, 2015 at 11:32

1 Answer 1

3

boost::shared_ptr<> is not designed to be used to hold an array that's "decayed" to a pointer.

For starters, it wouldn't delete the memory correctly on destruction (it would call delete rather than delete[].) You'd have to build your own deallocator to circumvent this. Possible but tedious.

Keep things simple: use std::vector<float>. In the current standard, the underlying data are guaranteed to be contiguous, and data() can be used to extract the underlying array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I finally understand why I was getting an error message. Besides that as you mentioned std::vector<>. If I use instead just float value[9] = {} to allocate memory do you think it is good.

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.