c – 复制构造函数需要与temp对象

前端之家收集整理的这篇文章主要介绍了c – 复制构造函数需要与temp对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码仅在复制构造函数可用时有效.

当我添加打印语句(通过std :: cout)并使拷贝构造函数可用时,它不会被使用(我认为这样编译器的技巧就是删除不必要的拷贝).

但是在输出运算符<和下面的函数plop()(我创建一个临时对象)我看不到复制构造函数的需要.当我通过const引用传递所有内容(或者我做错了什么)时,有人可以解释为什么语言需要它.

#include <iostream>

class N
{
    public:
        N(int)  {}
    private:
        N(N const&);
};

std::ostream& operator<<(std::ostream& str,N const& data)
{
    return str << "N\n";
}

void plop(std::ostream& str,N const& data)
{
    str << "N\n";
}

int main()
{
    std::cout << N(1);     // Needs copy constructor  (line 25)
    plop(std::cout,N(1));  // Needs copy constructor

    N    a(5);
    std::cout << a;
    plop(std::cout,a);
}

编译:

[Alpha:~/X] myork% g++ -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5646~6/src/configure –disable-checking –enable-werror –prefix=/usr –mandir=/share/man –enable-languages=c,objc,c++,obj-c++ –program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ –with-slibdir=/usr/lib –build=i686-apple-darwin10 –with-gxx-include-dir=/include/c++/4.2.1 –program-prefix=i686-apple-darwin10- –host=x86_64-apple-darwin10 –target=i686-apple-darwin10
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5646)

[Alpha:~/X] myork% g++ t.cpp
t.cpp: In function ‘int main()’:
t.cpp:10: error: ‘N::N(const N&)’ is private
t.cpp:25: error: within this context
t.cpp:10: error: ‘N::N(const N&)’ is private
t.cpp:26: error: within this context

这是一些真实代码的简化版本.
在真正的代码中,我有一个包含std :: auto_ptr的类.这意味着一个引用const引用的复制构造函数是无效的(没有一些工作),而且我收到一个错误,指出拷贝构造函数不可用:

改变课程:

class N
{
    public:
        N(int)  {}
    private:
        std::auto_ptr<int>  data;
};

那么错误是:

t.cpp:25: error: no matching function for call to ‘N::N(N)’

解决方法

http://gcc.gnu.org/gcc-3.4/changes.html

When binding an rvalue of class type
to a reference,the copy constructor
of the class must be accessible. For
instance,consider the following code:

class A 
{
public:
  A();

private:
  A(const A&);   // private copy ctor
};

A makeA(void);
void foo(const A&);

void bar(void)
{
  foo(A());       // error,copy ctor is not accessible
  foo(makeA());   // error,copy ctor is not accessible

  A a1;
  foo(a1);        // OK,a1 is a lvalue
}

This might be surprising at first
sight,especially since most popular
compilers do not correctly implement
this rule (07001).

这将通过Core Issue 391在C 1x中修复.

原文链接:https://www.f2er.com/c/116297.html

猜你在找的C&C++相关文章