是否可以在 C++ 中声明 operator= private 并同时由编译器合成它?

发布于 12-28 17:11 字数 365 浏览 1 评论 0原文

我对运算符 = 很满意,它是由编译器自动合成的。但我希望它是私有的,并且不想用类型的页面长定义来膨胀我的代码

Foo& Foo::operator= (const Foo& foo)
{
    if (this == &foo)
        return *this;

    member1_    = foo.member1_;
    member2_    = foo.member2_;
    member3_    = foo.member2_;
    ...
    member1000_ = foo.member1000_;

    return *this;
} 

,有没有办法做到这一点?

I am happy with the operator =, which is synthesized by the compiler automatically. But I want it to be private and do not want to bloat my code with page long definitions of the type

Foo& Foo::operator= (const Foo& foo)
{
    if (this == &foo)
        return *this;

    member1_    = foo.member1_;
    member2_    = foo.member2_;
    member3_    = foo.member2_;
    ...
    member1000_ = foo.member1000_;

    return *this;
} 

Please, is there a way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清秋悲枫2025-01-04 17:11:11

在 C++11 中是:

class Foo
{
    Foo& operator=(const Foo& source) = default;
public:
    // ...
};

不幸的是,大多数编译器还没有实现新标准的这一部分。

In C++11 it is:

class Foo
{
    Foo& operator=(const Foo& source) = default;
public:
    // ...
};

Unfortunately, most compilers haven't implemented this part of the new standard yet.

じ违心2025-01-04 17:11:11

另一种选择是使用 Pimpl 惯用法。

class Foo {
public:
    Foo() : pImpl(new FooImpl) {}
    // ... Foo's public interface, same as before
private:
    Foo& operator=(const Foo& source);  //- Foo's assignment operator is private

    struct FooImpl;
    boost::scoped_ptr<FooImpl>  pImpl;
};

struct FooImpl {
    // ... all the private data members that use to be in Foo
    // Note: using the compiler generated copy assignment operator
};  

复制赋值运算符对于 Foo 客户端的 POV 来说是私有的,但您仍然可以通过 FooImpl 利用编译器生成的复制赋值。在实现 Foo 的成员函数时需要进行权衡,因为您现在必须通过 pImpl 指针访问数据。

Another option is to use the Pimpl idiom.

class Foo {
public:
    Foo() : pImpl(new FooImpl) {}
    // ... Foo's public interface, same as before
private:
    Foo& operator=(const Foo& source);  //- Foo's assignment operator is private

    struct FooImpl;
    boost::scoped_ptr<FooImpl>  pImpl;
};

struct FooImpl {
    // ... all the private data members that use to be in Foo
    // Note: using the compiler generated copy assignment operator
};  

The copy assignment operator is private from the POV of Foo clients but you can still leverage the compiler generated copy assignment via FooImpl. The tradeoff comes when implementing Foo's member functions as you now have to access the data through the pImpl pointer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文