【问题标题】:What the author is trying to say in GotW #53?作者在 GotW #53 中想说什么?
【发布时间】:2013-07-07 12:53:55
【问题描述】:

这个伪代码是从GotW #53 获得的,标题为“A Not-So-Good Long-Term Solution”。几个小时以来,我一直在试图理解作者在说什么,特别是与下面以“//错误:潜在......”开头的评论有关,但无济于事。我真的很感激这方面的一些帮助。

    //  Example 2c: Bad long-term solution (or, Why to
    //              avoid using declarations in
    //              headers, even not at file scope)
    //
    //--- file x.h ---
    //
    #include "y.h"  // declares MyProject::Y and adds
                    //  using declarations/directives
                    //  in namespace MyProject
    #include <deque>
    #include <iosfwd>
    namespace MyProject
    {
      using std::deque;
      using std::ostream;
      // or, "using namespace std;"
      ostream& operator<<( ostream&, const Y& );
      int f( const deque<int>& );
    }
    //--- file x.cpp ---
    //
    #include "x.h"
    #include "z.h"  // declares MyProject::Z and adds
                    //  using declarations/directives
                    //  in namespace MyProject
      // error: potential future name ambiguities in
      //        z.h's declarations, depending on what
      //        using declarations exist in headers
      //        that happen to be #included before z.h
      //        in any given module (in this case,
      //        x.h or y.h may cause potential changes
      //        in meaning)
    #include <ostream>
    namespace MyProject
    {
      ostream& operator<<( ostream& o, const Y& y )
      {
        // ... uses Z in the implementation ...
        return o;
      }
      int f( const deque<int>& d )
      {
        // ...
      }
    }

【问题讨论】:

  • 作者试图告诉人们不要将using声明或指令放在头文件中。
  • @juanchopanza 好的,但我不明白他的推理。

标签: c++ header-files using-declaration gotw


【解决方案1】:

作者说这段代码的问题在于,由于这段代码在其他应用程序中使用,可能会有多个同名的事物(“潜在的未来命名空间歧义”),具体取决于其他应用程序中使用的命名空间头文件。如果他们说应该使用不同的命名空间,那么相同的名称可能不会指向作者最初的意图。

【讨论】:

    【解决方案2】:

    他的意思是不要在头文件中使用using 指令。例如:假设我们有 2 个带有这些声明的文件 x.h 和 z.h:

    // x.h
    namespace MyProject
    {
      using std::deque;
      using std::ostream;
      ....
    };
    
    // z.h
    namespace MyProject
    {
      using mystd::deque;
      using mystd::ostream;
      ....
    };
    

    问题是:在您的示例中将调用哪个 ostream 对象?

    // x.cpp
    #include "x.h"
    #include "z.h"
    #include <ostream>
    namespace MyProject
    {
      ostream& operator<<( ostream& o, const Y& y )
      {
        // ... uses Z in the implementation ...
        return o;
      }
      int f( const deque<int>& d )
      {
        // ...
      }
    }
    

    您想调用x.h 定义,但由于包含的顺序,它将调用z.h 包含定义

    【讨论】:

    • 您的答案中没有使用指令。 using std::deque; 是 using 声明,而不是 using 指令。
    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多