Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我正在尝试制作我自己的vector版本';s在C+中交换+;03和am完全被错误卡住/阻挡_C++ - Fatal编程技术网

C++ 我正在尝试制作我自己的vector版本';s在C+中交换+;03和am完全被错误卡住/阻挡

C++ 我正在尝试制作我自己的vector版本';s在C+中交换+;03和am完全被错误卡住/阻挡,c++,C++,我正在尝试在我的vector类版本中创建一个swap方法,该类使用C++03格式而不使用boost。我目前拥有的代码是 template <class T> void kvector<T>::swap(kvector<T> &in) { kvector<T>* temp = &in; //copying the pointer of in into temp and therefore bypassing the assig

我正在尝试在我的vector类版本中创建一个swap方法,该类使用C++03格式而不使用boost。我目前拥有的代码是

template <class T>
void kvector<T>::swap(kvector<T> &in)
{
    kvector<T>* temp = &in; //copying the pointer of in into temp and therefore bypassing the assignment operator
    //now switch in and this and than this and temp using pointer arithmetic to again bypass the assignment operator
    //!note: the pointer based arithmetic used in this swap method is exponentially faster than using an
    //!assignment operator or copy constructor

    &in = this;
    this = temp;
    //!no need to set the data pointer of temp to 0 since temp is a pointer and will not get
    //!deleted automatically. Since both in and this still exist at the end of this method
    //!than no memory can leak from this method
}
模板
void kvector::swap(kvector&in)
{
kvector*temp=&in;//将in的指针复制到temp中,从而绕过赋值运算符
//现在,使用指针算法再次绕过赋值运算符,切换入和this和than this和temp
//!注意:此交换方法中使用的基于指针的算法比使用
//!赋值运算符或复制构造函数
&in=这个;
这=温度;
//!无需将temp的数据指针设置为0,因为temp是一个指针,不会获取
//!已自动删除。因为在该方法结束时,中和中仍然存在
//!则此方法不会泄漏内存
}

它试图将向量作为指针传递。我从
&in=this
此=温度。错误是表达式“不可赋值”。我只是不明白这个错误意味着什么,为什么这是一个错误。有人能解释一下吗?我很困惑。

通常,您会交换
kvector
的成员变量。你为什么不那样做?此外,您不能更改引用指向的对象,这是您在第二行中尝试执行的操作。您也无法更改此
指向的内容,这是您在第三行尝试执行的操作。您无法将某些内容分配给对象的地址。它会留在记忆中。哦,这就是发生的事情。好吧,这是有道理的。我应该在中创建向量的临时副本,而不是交换成员变量吗?为什么要将
swap
的vrrsion限制为向量?如果它有效,它应该适用于每种类型。事实上,它是如此普遍,人们会期望它被植入语言中。你想问问自己,wjy,事实并非如此,“我应该做一个向量的临时副本吗?”。如果您想彻底挫败
交换的目的,即避免复制,请继续。