Object declaration in try and catch is not defined in scope

I would like to declare an object in a try / catch statement like this:

try {
  Object object(value);
} catch (exception) {
  return 1;
}
object.usingExemple();

g ++ tells me that the object is not defined in scope.

I understand that if try receives an exception object, it is not created and cannot be used. But don't g ++ know that I will leave the function if this happens?

How can I declare an object that throws an exception in the constructor without using a new one?

Thank you in advance:)

+4
source share
1 answer

: object , ( , , ), , . object try:

try {
  Object object(value);
  object.usingExemple();
} catch (exception) {
  return 1;
}

: try , . - object .


, , , usingExample(), ( @immibis ). , :

std::unique_ptr<Object> objectPtr;
try {
  objectPtr.reset(new Object(value));
} catch (exception)
  return 1;
}
Object &object = *objectPtr;
object.usingExample();

new, " ":

alignas(Object) unsigned char objectStorage[sizeof(Object)];
Object *objectPtr;
try {
  objectPtr = new (&objectStorage) Object(value);
} catch (exception) {
  return 1;
}
try {
  Object &object = *objectPtr;
  object.usingExample();
} catch (...) {
  objectPtr->~Object();
  throw;
}
+4

All Articles