繁体   English   中英

这是 C++ Builder 或 MinGw 和 MSVC 中的错误吗?

[英]Is this a bug in C++ Builder or in MinGw, and MSVC?

下面的代码基于CPP 核心指南,附录 C,“讨论:如果在初始化期间需要“虚拟行为”,请使用工厂 function”

该代码的想法是使用工厂 function 实例化派生类,这些派生类需要在派生 class 中调用“后构造函数”。

我的代码是这样的:

#include <iostream>
#include <memory>

using namespace std;

class B {
protected:
    class Token {};

public:
    // constructor needs to be public so that make_shared can access it.
    // protected access level is gained by requiring a Token.
    explicit B(Token) { /* ... */ }  // create an imperfectly initialized object

    template<class T>
    static shared_ptr<T> create()    // interface for creating shared objects
    {
        auto p = make_shared<T>(typename T::Token{});
        p->post_initialize();
        return p;
    }

private: //change to protected and it compiles in C++ Builder
    void post_initialize()   // called right after construction
    { /* ... */ f(); /* ... */ } // GOOD: virtual dispatch is safe
    virtual void f() = 0;
};


class D : public B {                 // some derived class
protected:
    class Token {};

public:
    // constructor needs to be public so that make_shared can access it.
    // protected access level is gained by requiring a Token.
    explicit D(Token) : B{ B::Token{} } {}
    D() = delete;

protected:

    //Make B:create() a friend so it can access private and protected members...

    template<class T>
    friend shared_ptr<T> B::create();

private: 

    void f() override {
        std::cout << "I'm a D" << std::endl;
    };
};


int main() {

    shared_ptr<B> p = B::create<D>();    // creating a D object

    return 0;
}

此代码使用 MinGW 版本 w64 9.0 和 MSVC 2022 编译和运行。但是,C++Builder 11.5 Alexandria,Clang 编译器,32 位和 64 位,抱怨:

错误:“post_initialize”是“B”的私有成员

但是,如果我将 class Bprivate:部分更改为protected: ,C++Builder 会编译代码。

我希望 C++Builder 能够编译它,因为B::create()应该能够调用Bprivate function,不是吗?

或者,我错了吗,MinGW 和 MSVC 无法正确编译它?

我希望 C++ Builder 将其编译为 B::create() 应该能够调用 B 的私有 function 不是吗?

是的,允许从B::create()内部像p->post_initialize() post_initialize使用/调用 post_initialize,因为它们都属于同一个 class。

根据您的错误描述,这看起来像 C++ Builder 错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM