使用operator =()时使用copy-ctor的C ++ - 究竟是如何工作的?

时间:2014-04-12 02:08:42

标签: c++ assignment-operator construction

C ++将operator =()赋值转换为构造的规则究竟是什么?例如Foo foo = bar实际上会调用Foo的构造函数接受bar作为参数,如果它存在的话。我用谷歌搜索了它是如何工作但似乎找不到任何东西。

我遇到一个问题,弄清楚为什么下面的任务试图采用一个构造函数,但没有采用明显正确的一个:HandlePtr(TYPE& resource)。使用实际构造语法的构造工作正常,但不能使用赋值运算符。

代码(显然是为了简洁而编辑):

template< typename TYPE >
class HandlePtr {
public:
    HandlePtr( void ) = default;
    HandlePtr( HandlePtr< TYPE >& other ) = default;
    HandlePtr( TYPE& resource ) {} // generally I would make this explicit, but for testing purposes I took it out
    ~HandlePtr( void ) = default;

public:
    HandlePtr<TYPE>& operator=( TYPE& resource ) { return *this; }
    HandlePtr<TYPE>& operator=( HandlePtr<TYPE>& other ) { return *this; }
};

int main ( void ) {
    int x = 5;
    HandlePtr< int > g( x ); // works
    HandlePtr< int > i;i = x; // works
    HandlePtr< int > h = x; // doesn't work

            // also tried this just out of curiosity:
    HandlePtr< int > h = HandlePtr< int >( x ); // also does not work

    return 0;
}

错误:

shit.cpp: In function ‘int main()’:
try.cpp:19:24: error: no matching function for call to ‘HandlePtr<int>::HandlePtr(HandlePtr<int>)’
   HandlePtr< int > h = x; // doesn't work
                        ^
try.cpp:19:24: note: candidates are:
try.cpp:7:3: note: HandlePtr<TYPE>::HandlePtr(TYPE&) [with TYPE = int]
   HandlePtr( TYPE& resource ) {} // generally I would make this explicit, but for testing purposes I took it out
   ^
try.cpp:7:3: note:   no known conversion for argument 1 from ‘HandlePtr<int>’ to ‘int&’
try.cpp:6:3: note: HandlePtr<TYPE>::HandlePtr(HandlePtr<TYPE>&) [with TYPE = int]
   HandlePtr( HandlePtr< TYPE >& other ) = default;
   ^
try.cpp:6:3: note:   no known conversion for argument 1 from ‘HandlePtr<int>’ to ‘HandlePtr<int>&’
try.cpp:5:3: note: HandlePtr<TYPE>::HandlePtr() [with TYPE = int]
   HandlePtr( void ) = default;
   ^
try.cpp:5:3: note:   candidate expects 0 arguments, 1 provided
try.cpp:20:20: error: redeclaration of ‘HandlePtr<int> h’
   HandlePtr< int > h = HandlePtr< int >( x ); // also does not work
                    ^
try.cpp:19:20: error: ‘HandlePtr<int> h’ previously declared here
   HandlePtr< int > h = x; // doesn't work

1 个答案:

答案 0 :(得分:2)

您在声明

中忽略了这一点
T t = u;

这不是赋值运算符。 t = u;不是声明的子表达式。这里唯一的表达是u;评估表达式u的结果用作声明的对象t的初始值。

如果u的类型为T,则tu复制构建的。{/ p>

如果u没有T类型,则首先需要将u转换为T类型。这会创建T类型的 rvalue

您没有任何接受右值的构造函数,因此T t = u;和相同的T t = T(u);都会失败。但是,T t(u)成功,因为没有创建右值;值u用作构造函数T(U &)的参数。

简化代码示例:

struct T
{
    T(int &);
    T(T&);
    T();
    T &operator=(int &);
};

int main()
{
    int x = 5;
    T g(x);   // OK, T(int &)
    T g2(5);   // fail, looks for T(int const &)
    T i;      // OK, T()
    i = x;    // OK, T::operator=(int&)
    T h3 = i; // OK, T(T&)
    T h1 = T(x);    // fail, looks for T(T const &)
    T h2 = x;       // fail, identical to previous line 
}

通常你应该使用const &作为copy-constructors和赋值运算符的参数;然后所有这些“失败”的情况变为“OK”,因为rvalue可以绑定到const引用。