【问题标题】:how to handle wrong value passing to constructor parameters?如何处理传递给构造函数参数的错误值?
【发布时间】:2015-10-01 17:42:45
【问题描述】:

我有我的班级堆栈

class Stack
{
public:
    Stack(unsigned int Size)
   {
    size = Size;
   }

private:
    unsigned int size;
    void* Block;
};

int _tmain(int argc, _TCHAR* argv[])
{
    Stack x(-1);
    return 0;
}

我想确保即使我将负值传递给构造函数参数 该对象不会被构造,但是当我给出 -1 值时,它正在接受它并且变量大小值为 4294967295 ,据我所知,在删除 sing 位后与 -1 相同 ...

那么我该如何处理这种情况呢?我应该抛出异常吗?或者只是在错误值的情况下取默认值?

【问题讨论】:

  • 根据您的编译器,您至少可以获取compilation warnings 以将有符号值作为无符号参数传递。至于在运行时......你可能是 SOL,因为这种行为是 specified by the standard
  • 在 _tmain 函数中使用“try catch”处理程序并在类构造函数中抛出异常。检查cplusplus.com/doc/tutorial/exceptions
  • @user2340218 发现了什么?不会有例外。
  • 什么都不做,不要和愚蠢的程序员打架。在这种情况下,崩溃是一个可行的结果。

标签: c++ error-handling type-conversion parameter-passing


【解决方案1】:

如果您使用 Visual C++ 编译器 (MSVC),作为一般规则,您可能希望在 /W4 编译您的代码(即警告级别 4),因此编译器会发出声音更频繁,并有助于识别程序员的错误。

例如:

C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp

warning C4245: 'argument' : conversion from 'int' to 'unsigned int',
signed/unsigned mismatch

编辑

此外,您可能希望将构造函数标记为 explicit,以避免从整数到 Stack 类实例的隐式虚假转换。

【讨论】:

  • @AlphasSupremum 带有显式关键字
  • @AlphasSupremum:只需使用explicit Stack(unsigned int Size) 语法。相关SO question here.
【解决方案2】:

我想确保即使我将负值传递给构造函数 对象不会被构造的论点

一种方法是-Wsign-conversion -Werror

$ clang++ -Werror -Wsign-conversion -c stack.cpp
stack.cpp:18:13: error: implicit conversion changes signedness: 'int' to 'unsigned int' [-Werror,-Wsign-conversion]
    Stack x(-1);
          ~ ^~
1 error generated.


$ cat stack.cpp

class Stack
{
    public:
        Stack(unsigned int Size)
        {
            size = Size;
        }

    private:
        unsigned int size;
        void* Block;
};

typedef const char _TCHAR;
int _tmain(int argc, _TCHAR* argv[])
{
    Stack x(-1);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多