我的字符串C ++的构造函数 [英] constructors of my string C++

查看:116
本文介绍了我的字符串C ++的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果构造函数中的某些操作失败,则必须抛出异常。这是否意味着每次我在构造函数中使用 new时,在创建此类的对象时都应在 try catch块中对其进行初始化?

I know that if something in the constructor fails, I must throw an exception. Does this mean everytime I use 'new' inside of my constructors, when I create an object of this class I should initialise it in the 'try' 'catch' block?

try{
mystring s("test");
}
catch(std::ba .....)
{...........}

我知道新几乎不可能失败,但是我要问的是,如果我的构造函数抛出了某些东西,这是否是正确的方法它? (因为我从未见过有人在创建对象时使用它)

I know that is almost impossible 'new' to fail, but what I'm asking is, if my constructor throws something, is this the right way to catch it? (because I've never seen someone using it when creating an object)

推荐答案

您真的应该在每个这样的语句中放入 try {} catch {} 。正确使用 exceptions 的妙处在于,您不必担心整个代码区的异常,如果某个组件的某个组件发生故障,则整个代码区将无法运行。不要检查单个语句,请检查代码的整个子节。

You really should not be putting a try{}catch{} round every statement like that. The beauty of exceptions is, when used correctly, that you don't have to worry about exception for an whole area of code that can not function if one of its components fails. Don't check the individual statements, check the entire sub-section of code.

try
{
    // good chunk of code that requires everything to succeed

    object o1; // if this fails we can't continue

    auto o2 = o1.func(); // if this fails we can't continue
    auto o3 = o2.func(); // if this fails we can't continue

    return o3; // yay we got there
}
catch(const std::exception& e)
{
    // that entire task failed because e.what(), tell the user and move on
}

关键是要确保您的对象自己清理抛出异常时的析构函数。这就是 RAII 方法。

The crucial thing is to ensure your objects clean themselves up in their destructors when an exception is thrown. That is the RAII approach.

这篇关于我的字符串C ++的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆