Reputation: 11
I am a C++ beginner and I am writing a class in C++ and I am using std::string
.
How do I handle bad_alloc
exception?
Can I do:
Temp::Temp(const string name) :
{
try {
name(name);
}
catch(std::bad_alloc& a) {
cout << "bad alloc error" << endl;
}
}
or should I do
Temp::Temp(const string name) :
name(name)
{
catch(std::bad_alloc& a) {
cout << "bad alloc error" << endl;
}
}
I want to catch the exception so that I would be able to prevent memory leak, and then maybe throw it again.
Also when I use x.assaing(y)
from std::string
do I have to check for bad_alloc
exception too? (If I want to handle memory leaks.)
I am looking for a way without smart pointers (we didn't learn it yet).
Upvotes: 0
Views: 954
Reputation: 12174
Initializing a member of type std::string
via constructor in a member initializer list won't cause memory leak.
#include <string>
struct Temp
{
Temp (const std::string& name): name(name) {}
std::string name;
};
Temp t ("yourname");
std::cout << t.name; // yourname
UPDATE: (suggested by @Deduplicator)
If only using one ctor, might as well use std::string_view
which is a:
constant contiguous sequence of
char
-like objects
Like:
#include <string_view>
struct Temp
{
Temp (std::string_view name): name(name) {}
std::string name;
};
Temp t ("yourname");
std::cout << t.name; // yourname
Upvotes: 1
Reputation:
If string construction does throw bad_alloc there is very little you can do to recover from it. You certainly should not be wrapping each construction of a string in a try-block. Instead you should allow the exception to bubble up to a higher level, such as your main function, catch it there, report the error somehow, and probably terminate the program. In general, you want to catch exceptions at the highest possible level that they can sensibly be handled.
Upvotes: 0