gpt4 book ai didi

C++ 类构造函数抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:34 24 4
gpt4 key购买 nike

让我们考虑拥有一个,其中包含一个构造函数并抛出一个异常 如下所示:

class Class
{
public:
Class(type argument)
{
if (argument == NULL)
{
throw std::exception("Value cannot be null.\nParameter name: argument");
}

// Instructions
}
private:
// Properties
}

因为 class constructor 可能会抛出一个exception 我们不能直接声明一个对象

Class obj(argument); // Harmful

这意味着必须调用构造函数 必须使用try/catch

try
{
Class obj(argument);
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
}

问题是我们只能在 try block 中使用 object。在 try block 之外使用它的唯一方法是声明一个 Class* pointer/strong> 然后使用 new 关键字构造一个新的 object 然后将它的地址分配给之前的 >指针

Class* pObj;

try
{
pObj = new Class(argument);
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
}

那么为了在不使用指针的情况下创建实例,定义前面的的标准方法是什么?还是动态内存分配?

提前致谢

最佳答案

Since the class constructor might throw an exception we cannot declare an object directly.

是的,你可以。如果您确实有计划在函数中处理异常,则只需将其放在 try block 中。如果您没有这样的计划,那么就让异常传播(尽管您最终应该捕获它,如果没有别的,只是为了提供报告)。

但是,假设您确实有计划在函数中处理异常,那么解决方案很简单。

try {
Class obj(argument);
// use obj here, inside the try block
}
catch(...) { ... }

// not here, outside the try block

编辑:根据您在下方的评论,要么是您误解了我,要么是我误解了您。也许需要一个具体的例子。假设这是使用您的类的函数:

void Foobar(type argument)
{
Class obj(argument);
obj.method1(1,2,3);
obj.method2(3,4);
int x = Wizbang(obj);
gobble(x);
}

现在,您要处理 Class 构造函数可能抛出的异常。我的建议是将函数中的所有垃圾放入 try block 中,因此:

void Foobar(type argument)
{
try
{
Class obj(argument);
obj.method1(1,2,3);
obj.method2(3,4);
int x = Wizbang(obj);
gobble(x);
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

如果您不能这样做,请说明原因。您曾说过“我需要访问权限才能稍后使用该对象”,但您没有说明为什么“稍后”不能表示“稍后在同一对象中”尝试在创建对象的地方阻止”。因此,您的要求不完整。

关于C++ 类构造函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25756495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com