如何处理传递给构造函数参数的错误值?

how to handle wrong value passing to constructor parameters?

我有我的 class 堆栈

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 ...

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

I want to make sure that even I pass negative value to the constructor argument that the object wont be constructed

一种方法是 -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;
}

如果您使用的是 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 class.

实例的隐式伪造转换