更改操作的构造函数顺序
Change constructor order of operations?
我有以下示例代码,复制赋值正在做一些我不想要的事情 - 它首先构造新的 samp(6(,然后将其复制到 z,然后销毁它构建的新 samp(6(。有没有办法改变构造函数,使 = 像指针一样,销毁最初构造的 samp(5( 并用新的 samp(6( 替换它,在 samp(5( 上调用析构函数,而不是 samp(6(?
#include <iostream>
class samp
{
public:
samp(int a)
{
m_a = a;
std::cout << "cons" <<m_a << std::endl;
}
int m_a;
samp(const samp& other)
{
std::cout << "copy" << m_a << std::endl;
m_a = other.m_a;
}
samp& operator= (const samp& other)
{
std::cout << "assg" << m_a << std::endl;
samp* z =new samp(other.m_a);
return *z;
}
~samp()
{
std::cout << "dest" <<m_a<< std::endl;
}
};
int main()
{
samp z(5);
z = samp(6);
std::cout << z.m_a << std::endl;
return 0;
}
也许指针语义是你想要的:
#include <memory>
// ...
auto z = std::make_unique<samp>(5);
z = std::make_unique<samp>(6); // dest5
std::cout << z->m_a << 'n'; // 6
尽管如果您从对象名称是对象引用的语言C++,最好习惯于C++值语义,而不是尝试复制对象引用:)
operator=
是对象的成员,因此this
指针可用。此外,分配意味着分配的目标应该改变。您的版本正在创建一个新对象,但保留目标。看看这是否符合您的要求:
samp& operator= (const samp& other)
{
m_a = other.m_a;
return *this;
}
相关文章:
- 类内初始化与构造函数初始化列表的顺序
- 运算符 new 的执行顺序和构造函数的参数
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 构造函数中没有参数的对象类成员按什么顺序初始化?
- 用作成员构造函数参数的函数的求值顺序
- 函数中调用的构造函数的顺序
- 构造函数中初始化列表的计算顺序是否固定?
- 构造函数和析构函数的顺序
- 遵循 C++ 中的构造函数执行顺序
- 更改操作的构造函数顺序
- 构造函数的初始值设定项列表中的函数调用是否按顺序排序?
- 如何维护类成员的顺序,并且仍然有一个可工作的构造函数
- 在继承中更改构造函数的顺序
- C++:初始值设定项列表顺序中的构造函数
- 如何在使用 std::make_tuple 时避免构造函数的未定义执行顺序
- 程序不会按照构造函数进行顺序进行,从而导致非初始化的变量
- 构造函数的调用顺序
- 构造函数和析构函数调用的顺序
- C++构造函数顺序
- 虚拟继承构造函数顺序