在打包代码中使用命名空间的最佳/最干净方法是什么?
例如在像boost这样的库中似乎有非常有组织的命名空间管理,使用了一些允许消除名称歧义的技术.然而,重要的是,人们不会看到很多代码
typedef namespace1::namespace2::sth_else::a_class<namespace3::namespace4::b_class> type;
Run Code Online (Sandbox Code Playgroud)
通常,没有太多的跨名称空间,这表明良好的体系结构,但也有良好的命名空间管理.问题是:什么是良好的命名空间管理?
假设我们有这样的文件结构:
component1/... (depends on reusable_if)
component2/... (depends directly on reusable_if and on component 1)
reusable/
reusable/some_part/
reusable/some_part/...
reusable/some_other_part/
reusable/some_other_part/...
reusable/SthThatUsesBothReusableParts.h (implements reusable_if/ISth.h)
reusable/SthThatUsesBothReusableParts.cpp (implements reusable_if/ISth.h)
reusable_if/
reusable_if/ISth.h (pure abstract class)
reusable_if/ISthElse.h (pure abstract class)
main.cpp (e.g. instantiates SthThatUsesBothReusableParts and passes to component1/2)
Run Code Online (Sandbox Code Playgroud)
存在reusable_if /文件夹的原因是因为component1和component2都想重用相同的接口(因此它们都没有'独占'接口).此外,假设项目确实非常大,并且需要为每个文件夹中的类提供适当的名称空间.
如何在这样的项目中应用名称空间?假设我在可重用/在命名空间中声明所有类::reusable.我应该将reusable_if中的接口放入命名空间::reusable还是放入::reusable_if?或者也许没有,因为它被component1和component2使用?
component1和component2中的命名空间怎么样?有什么要记住的吗?关键字using怎么样?假设我决定添加此::reusable_if命名空间.我可以把using reusable_if成头文件中COMPONENT1和COMPONENT2,只要using ...放在里面的命名空间::component1和::component2?
我愿意接受任何建议,也不一定与上述例子有关.
假设我定义了一个以下的C++对象:
class AClass
{
public:
AClass() : foo(0) {}
uint32_t getFoo() { return foo; }
void changeFoo() { foo = 5; }
private:
uint32_t foo;
} aObject;
Run Code Online (Sandbox Code Playgroud)
该对象由两个线程T1和T2共享.T1经常getFoo()在循环中调用以获得一个数字(如果changeFoo()以前没有被调用,它将始终为0 ).在某些时候,T2调用changeFoo()它来改变它(没有任何线程同步).
是否有任何实际的机会有史以来T1获得的值会有所不同比0或5 的现代计算机体系结构和编译器?到目前为止我调查的所有汇编代码都使用32位内存读写,这似乎可以节省操作的完整性.
其他原始类型呢?
实际意味着您可以提供现有体系结构或符合标准的编译器的示例,其中理论上可以实现此(或具有不同代码的类似情况).我把" 现代"这个词留下了一点主观.
编辑:我可以看到很多人注意到我不应该期待5被读.这对我来说完全没问题,我没有说我这么做(虽然感谢你指出这方面的问题).我的问题更多的是关于上述代码可能发生什么样的数据完整性违规.
在C++中,无论我在web中看到后缀增量运算符声明的示例,它总是被声明为
T& operator++(int);
Run Code Online (Sandbox Code Playgroud)
而且我相信这是后缀增量的正确语法,不是吗?
问题在于,每当我声明后缀增量时,我都会使用const关键字声明返回类型,以便它变为类似lvalue.
请参阅示例代码:
class AClass
{
int foo;
public:
AClass(void) : foo(0) {};
// Suffix increment operator
// Consider adding const to return type
/* const */ AClass operator++(int)
{
AClass cp(*this);
foo++;
return cp;
};
// Prefix increment operator
AClass& operator++()
{
foo++;
return *this;
};
};
int main(int argc, const char* args[])
{
/* This code would fail to compile.
int bar = 5;
(bar++)++;
*/
// Similarily, I would expect this to …Run Code Online (Sandbox Code Playgroud)