相关疑难解决方法(0)

关于RAII:如何防止意外创建临时错误?

有一段时间,一位同事告诉我,他花了很多时间来调试竞争条件.罪魁祸首竟然是这样的:

void foo()
{
    ScopedLock(this->mutex); // Oops, should have been a named object.
                             // Edit: added the "this->" to fix compilation issue.
    // ....
}
Run Code Online (Sandbox Code Playgroud)

为了防止情况再次发生,他在定义ScopedLock类之后创建了以下宏:

#define ScopedLock(...) Error_You_should_create_a_named_object;
Run Code Online (Sandbox Code Playgroud)

这个补丁工作正常.

有没有人知道任何其他有趣的技术来防止这个问题?

c++

10
推荐指数
2
解决办法
703
查看次数

这个AnonymousClass(变量)声明实际上发生了什么?

试图编译:

class AnonymousClass
{
public:
    AnonymousClass(int x)
    {
    }
};


int main()
{
    int x;
    AnonymousClass(x);
    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

从MSVC生成错误:

foo.cpp(13) : error C2371: 'x' : redefinition; different basic types
    foo.cpp(12) : see declaration of 'x'
foo.cpp(13) : error C2512: 'AnonymousClass' : no appropriate default constructor available
Run Code Online (Sandbox Code Playgroud)

g ++的错误消息类似:

foo.cpp: In function ‘int main()’:
foo.cpp:13: error: conflicting declaration ‘AnonymousClass x’
foo.cpp:12: error: ‘x’ has a previous declaration as ‘int x’
foo.cpp:12: warning: unused variable ‘x’
Run Code Online (Sandbox Code Playgroud)

通过给AnonymousClass对象一个明确的名称可以很容易地修复它,但是这里发生了什么以及为什么?我认为这是更多的声明语法怪异(如comp.lang.C++ FAQ的Q10.2 …

c++

7
推荐指数
1
解决办法
564
查看次数

标签 统计

c++ ×2