Reputation: 55
for example:
class Static {
public:
Static(std::vector<int> v) {
if (v.size() ! = 3) {
//...
}
}
~Static() {
std::cout << "Static dtor\n";
}
};
I have class named Static
, and its constructor has a argument v
, how can I check v
'size, and if v.size() < 3
, the constructor exit
many answers say that it can be solved by using throw
a exception, but the problem is that the destructor will not be call.
so I wonder whether return
will be ok, for examples:
class Static {
public:
Static(std::vector<int> v) {
if (v.size() ! = 3) {
//to log some error info
return;
}
}
~Static() {
std::cout << "Static dtor\n";
}
};
Upvotes: 1
Views: 80
Reputation: 8018
so I wonder whether return will be ok, for examples:
Most probably that's not OK, because it leaves you with a Static
instance in an invalid and improperly initialized state.
The only way to avoid that, and keep everything clean is throwing an exception.
Assumed you want to manage a std:.vector<int>
with a fixed size of 3 internally, it would be better to rewrite your constructor like
Static(int a, int b, int c) {
v_.push_back(a);
v_.push_back(b);
v_.push_back(c);
}
Upvotes: 1