当具有公共分配运算符的私有副本ctor时出错 [英] Error when have private copy ctor with public assignment operator

查看:96
本文介绍了当具有公共分配运算符的私有副本ctor时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们中的一个可以解释为什么下面的代码无法编译吗?

Can one of you explain why the following piece of code does not compile?

#include <iostream>

using namespace std;

class Foo
{
public:
  Foo() { cout << "Foo::Foo()" << endl << endl; }
  Foo& operator=(const Foo&) { cout << "Foo::operator=(const Foo&)" << endl << endl; }
private:
  Foo(const Foo& b) { *this = b; cout << "Foo::Foo(const Foo&)" << endl << endl; }
};

int main()
{
  Foo foo;

  foo = Foo();
}

我收到的错误:

$ g++ -o copy_ctor_assign copy_ctor_assign.cc && ./copy_ctor_assign
copy_ctor_assign.cc: In function 'int main()':
copy_ctor_assign.cc:10: error: 'Foo::Foo(const Foo&)' is private
copy_ctor_assign.cc:17: error: within this context

注意:当我删除 private: 关键字时,代码会编译,但永远不会调用复制ctor.那么,为什么它在私有状态下会出错呢?

Note: when I remove the private: keyword the code compiles but the copy ctor is never called. So why does it err when it's private?

不确定这是否重要,但我正在使用:

Not sure if it's important but I'm using:

$ g++ --version
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44)
Copyright (C) 2006 Free Software Foundation, Inc.

推荐答案

您正在初始化来自临时目录的引用.
标准状态:
应该使用非引用副本初始化的规则(8.5)初始化临时文件(8.5.3参数5).

You are initializing a reference from temporary.
The standard states:
The temporary should be initialized (8.5.3 par 5)"using the rules for a non-reference copy initialization (8.5)".

已删除临时副本的副本结构(标准允许.12.8par 5).
但是,该标准明确规定了(12.2标准1):
即使避免创建临时对象(12.8),也必须遵守所有语义限制,就像创建临时对象一样.[示例:即使未调用复制构造函数,所有语义限制(例如可访问性) (第11条),则应满足.]"

The copy construction is removed for the temporary (permitted by the standard. 12.8 par 5).
However, the standard clearly states (12.2 par 1):
"Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions must be respected as if the temporary object was created. [Example: even if the copy constructor is not called, all the semantic restrictions, such as accessibility (clause 11), shall be satisfied. ]"

(此外,当寻找正确的报价时,发现此

(also, when looking for the right quote, found this duplicate :)

从标准中添加相关位置

adding relevant location from the standard

这篇关于当具有公共分配运算符的私有副本ctor时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆