【问题标题】:c++11 forwarddeclare thread,mutex,chronoc++11 forwarddeclare thread,mutex,chrono
【发布时间】:2014-12-24 22:16:52
【问题描述】:

我知道我们应该更喜欢在头文件中转发声明所有内容,如果可能的话,但是 STL 呢?

我发现 iostreamiosfwd

如果我想在我的类中声明一个 mutex 怎么办,像这样:

class MyClass
{

.....
private:
    std::mutex mMutex;
};    

我应该在我的类头中包含互斥头吗? 或者有没有办法转发声明它,比如:

class std::mutex;
class MyClass{...};

chronothread 也是如此。

对此有任何想法。谢谢!

【问题讨论】:

  • 无论如何,您都需要std::mutex 的完整定义。编译器必须知道mMutex 的大小才能计算出MyClass 的大小。

标签: c++11 stl forward-declaration


【解决方案1】:

没有可移植的方式来转发声明 std::objects,除非指定(例如 <iosfwd>)。并且没有mutexthreadchrono 的转发标头。

【讨论】:

    【解决方案2】:

    C++ 11 标准规定,作为 std 命名空间一部分的前向声明类不能被前向声明(第 17.6.4.2.1 节):

    如果 C++ 程序添加声明或 定义到命名空间 std 或命名空间 std 内的命名空间 除非另有说明。

    但是由于某种原因,以下代码确实可以编译并运行。

    .h:

    #pragma once
    
    // Forward declaration of thread class that is part of the std namespace
    namespace std
    {
        class thread;
    }
    
    // Example declaration of a class using the forward declared class
    class ExampleClass
    {
        private:
            std::thread * _thread;
            void ThreadFunction(){}
    }
    

    .cpp

    #include "ExampleClass.h"
    #include <thread>
    
    ExampleClass::ExampleClass() :
        _thread(new std::thread(std::bind(&ExampleClass::ThreadFunction, this)))
    {
    
    }
    

    我使用 Visual Studio 2015 编译了代码,也许 C++ 11 标准语句不再适用于 C++14/17/20?

    【讨论】:

    • 正如您注意到标准中的声明所说的行为是“未定义的”。实现可以做的一种可能的、符合要求的事情是允许您的示例工作。但这并不表明标准发生了变化。
    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多