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.newexpression 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 usemake_sharedinstead. There are some situations where you shouldn’t (use ofweak_ptrto large objects), and some where you can’t (C++03 without Boost).deletethen 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.newsolely because the object is “too big for the stack”, consider writing a class that acts as a handle to the object, usingunique_ptrorscoped_ptrto 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 aunique_ptrto it, which you can then call likeauto foohandle = give_me_a_foo();. Thengive_me_a_foocontainsnew, 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”.