The more I read about RAII, I understand that using the stack is the way to make sure that the code is exception safe.
Does that mean every time I am doing a new()
in my code, I am doing something wrong in the sense there is a better way to do it using the RAII principle?
You're not necessarily doing something wrong if you use new
, but it's worth checking that you're doing it right.
new
expression should be immediately placed under the control of a smart pointer, usually by passing it straight into the constructor.shared_ptr
, then you are probably doing it wrong. You should probably use make_shared
instead. There are some situations where you shouldn't (use of weak_ptr
to large objects), and some where you can't (C++03 without Boost).delete
then you pretty much are doing it wrong, unless you are writing your own smart pointer class. And even then, your smart pointer might be able to use another smart pointer to save work.new
solely because the object is "too big for the stack", consider writing a class that acts as a handle to the object, using unique_ptr
or scoped_ptr
to manage it, so that from the user's point of view the objects they deal with are automatic variables. If you feel like it, you can extend this to the full PImpl idiom. Even if you don't want another class, consider a function that creates the object and returns a unique_ptr
to it, which you can then call like auto foohandle = give_me_a_foo();
. Then give_me_a_foo
contains new
, but other user code doesn't, and you encourage the practice of automatically stuffing things into RAII objects.There are alternative resource-management strategies to RAII in C++, but you'd know about it if you were using them, and that would affect what counts as "wrong".