0

我有一个由引用传递的另一个对象构造的对象。传递给构造函数的对象如下所示:

 HTTPServerResponse::HTTPServerResponse(Poco::Net::HTTPServerResponse &response)

我的包装类 ( HTTPServerResponse)response在某些时候会破坏,但它不会自行破坏。response实际上,即使在我的课堂之外,也有多种(外部)原因可能会被破坏。

我想要的是在调用任何其他方法response检查它的存在之前。

我试过了:

if(!response) {...

哪个产生了error C2675: unary '!' : 'Poco::Net::HTTPServerResponse' does not define this operator or a conversion to a type acceptable to the predefined operator;当然,我也尝试过:

if(response) {...

这也失败了error C2451: conditional expression of type 'Poco::Net::HTTPServerResponse' is illegal; No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

我该如何解决这个烂摊子?

4

3 回答 3

2

您永远无法知道您指向的引用或指针是否无效(请参阅为什么我不需要检查引用是否无效/空?)。

您只需要小心(并清楚)谁拥有引用/指针以及谁应该删除它。为了帮助获得所有权,您可以使用 std::unique_ptr 或 std::shared_ptr (在 C++0x 中,使用 boost 版本)。

于 2012-05-28T16:26:31.883 回答
0

我最终让整个线程保持忙碌,防止对象被删除,直到我完成它。我知道,这是乡巴佬,但它为我省去了在整个代码中进行乡巴佬的麻烦。

于 2012-05-28T19:57:19.727 回答
0

你真的必须知道对象是否存在吗?阅读接收器设计模式。它在 Boost Asio 中很常见。如果您使用的是指针,则必须记住在删除等之后为空指针...尝试使用 smart_ptr。

对我来说,很难想象为什么需要检查指针是否仍然存在。您的代码中存在设计问题。

于 2012-05-28T17:02:32.670 回答