gpt4 book ai didi

c++ - 避免在 C++ 中使用 undefined object

转载 作者:太空宇宙 更新时间:2023-11-04 14:46:57 25 4
gpt4 key购买 nike

如果我在 C++ 中创建一个类,则可以调用该类对象的函数,即使该类不存在也是如此。

例如:

类:

class ExampleClass
{
private:
double m_data;

public:
void readSomeData(double param)
{
m_data = param;
}
}

任何使用此类的函数:

int main()
{
ExampleClass* myClass;

myClass->readSomeData(2.5);
}

当然这不会起作用,因为 myClass 没有定义。为了避免这种情况,我检查 ExampleClass 对象是否是 null_ptr

例子:

void readSomeData(double param)
{
if(this == null_ptr)
return;

m_data = param;
}

但是 gcc 说:

'this' pointer cannot be null in well-defined C++ code; comparison may be assumed to always avaluate to false.

当然这只是一个警告,但我认为有这个警告并不好。有没有更好的方法来检查类的指针是否已定义?

最佳答案

在类中测试它是错误的方式,关于如果你的代码定义良好则 this 不能为 null 的警告是正确的,所以测试应该在你调用时发生成员函数:

int main()
{
ExampleClass* myClass = nullptr; // always initialize a raw pointer to ensure
// that it does not point to a random address

// ....

if (myClass != nullptr) {
myClass->readSomeData(2.5);
}

return 0;
}

如果指针在代码的特定部分不能为空,那么你应该根据 CppCoreGuideline: I.12: Declare a pointer that must not be null as not_null 来做

Microsoft 提供了一个 Guidelines Support Library具有 not_null 的实现。

或者如果可能的话,除了 std::optional 之外根本不使用指针。

因此代码设置可能如下所示:

#include <gsl/gsl>

struct ExampleClass {
void readSomeData(double ){}
};

// now it is clear that myClass must not and can not be null within work_with_class
// it still could hold an invalid pointe, but thats another problem
void work_with_class(gsl::not_null<ExampleClass*> myClass) {
myClass->readSomeData(2.5);
}

int main()
{
ExampleClass* myClass = nullptr; // always initialize a raw pointer to ensure
// that it does not point to a random address

// ....

work_with_class(myClass);

return 0;
}

关于c++ - 避免在 C++ 中使用 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237512/

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