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

C++ 是否可以在C+中声明operator=private并同时由编译器合成+;,c++,compiler-construction,operators,C++,Compiler Construction,Operators,我很满意运算符=,它是由编译器自动合成的。但我希望它是私有的,并且不希望使用该类型的页面长定义来扩充代码 Foo& Foo::operator= (const Foo& foo) { if (this == &foo) return *this; member1_ = foo.member1_; member2_ = foo.member2_; member3_ = foo.member2_; .

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

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;
} 
请问,有没有办法做到这一点?

在C++11中,它是:

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

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

另一种选择是使用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
};  
class-Foo{
公众:
Foo():pImpl(新FooImpl){}
//…Foo的公共界面,与以前相同
私人:
Foo&operator=(const-Foo&source);//-Foo的赋值运算符是私有的
结构FooImpl;
boost::作用域的ptr pImpl;
};
结构FooImpl{
//…所有用于存储在Foo中的私有数据成员
//注意:使用编译器生成的复制赋值运算符
};  

复制分配操作符是Foo客户端POV中的私有操作符,但您仍然可以通过FooImpl利用编译器生成的复制分配。在实现Foo的成员函数时需要权衡,因为您现在必须通过pImpl指针访问数据。

C++11一直让我感到惊讶。谢谢,这正是我想要的@user1097451:让我们知道它是否在你的编译器中工作(以及它是什么编译器):)gcc版本4.6.1(Ubuntu/Linaro 4.6.1-9ubuntu3)并且,不,它不工作,但我很高兴知道有一天它会工作:)经过一些调查,它是可能的,它工作了!还有我的编译器。它只需要一个额外的命令。引用:“GCC为2011 ISO C++标准提供实验支持。这个支持可以用-STD= C++ 11或-STD= GNU++11编译器选项来启用;前者禁用GNU扩展。”(见下文):P