使用指令最佳实践 [英] Using directive best practice

查看:61
本文介绍了使用指令最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容之间是否有 功能或优化方面的区别?

Is there any functional or optimization difference between the following?

// SomeClass.cpp
#include "SomeClass.h"
#include "SomeOtherClassInSomeClassNamespace.h"

using namespace SomeClassNamespace;

SomeClass::SomeClass() {}

void SomeClass::SomeFunc() 
{
    // uses some stuff in SomeClassNamespace not defined  in SomeClass.h
}

// SomeClass.cpp
#include "SomeClass.h"
#include "SomeOtherClassInSomeClassNamespace.h"

namespace SomeClassNamespace
{
    SomeClass::SomeClass() {}

    void SomeClass::SomeFunc() 
    {
        // uses some stuff in SomeClassNamespace not defined  in SomeClass.h
    }
}

推荐答案

以下内容是否有功能上的区别?

Is there any functional difference between the following?

只要合并的范围能够按预期解析,则.

As long as the merged scopes resolve as expected, then No.

以下内容之间是否存在优化差异?

Is there any optimization difference between the following?

运行时还是二进制大小? 否.

Runtime or binary size? No.

如果要进行 build 优化,则会通过using和/或重新打开命名空间来引入其他复杂性.

If you want build optimizations, then additional complexity will be introduced via using and/or by reopening the namespace.

我不使用前者,因为分辨率可能有问题.

I don't use the former because resolutions can be problematic.

我不使用后者,因为很容易以新的声明结尾.

I don't use the latter because it's easy to end up with new declarations.

我的使用方式:

namespace {
  // ... private stuff
}

SomeClassNamespace::SomeClass::SomeClass() {}
...

这有点冗长,但是如果使用匿名命名空间中的定义最终将其导出,则可以使用声明快速解析定义,减少冲突的机会,可以减少程序员的错误,并可以减小二进制大小(如果您还使用了私有实现).当然,将内部内容("SomeClassNamespace中的某些内容未在SomeClass.h中定义" )保留在正确的命名空间中也是有道理的(假设它们在多个TU中使用).

this is a little verbose, but fast to resolve definitions with their declarations, reduces chance of collisions, can reduce programmer errors, and could reduce binary size if the definitions in the anonymous namespace ends up being exported (in case you also use private implementations). Of course, it will also make sense to keep your internals ("some stuff in SomeClassNamespace not defined in SomeClass.h") in the right namespace (assuming they are used in multiple TUs).

这篇关于使用指令最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆