复制构造函数的这种实现有一些缺点吗?
Foo::Foo(const Foo& i_foo)
{
*this = i_foo;
}
Run Code Online (Sandbox Code Playgroud)
我记得,在某些书中建议从赋值运算符调用复制构造函数并使用众所周知的交换技巧,但我不记得了,为什么......
我有一些非常复杂的物体。它们包含其他对象的成员变量。我理解复制构造函数级联的美妙之处,这样默认的复制构造函数通常就可以工作。但是,最常破坏默认复制构造函数的情况(对象包含一些成员变量,它们是指向其其他成员变量的指针)仍然适用于我构建的很多内容。这是我的一个对象、它的构造函数和我编写的复制构造函数的示例:
struct PhaseSpace {
PhaseSpace();
private:
std::string file_name; ///< Name of the file from which these coordinates (and
///< perhaps velocities) derived. Empty string indicates
///< no file.
int atom_count; ///< The number of atoms in the system
UnitCellType unit_cell; ///< The type of unit cell
Hybrid<double> x_coordinates; ///< Cartesian X coordinates of all particles
Hybrid<double> y_coordinates; ///< Cartesian Y coordinates of all particles
Hybrid<double> z_coordinates; ///< Cartesian Z coordinates of all particles
Hybrid<double> box_space_transform; ///< Matrix to transform coordinates …Run Code Online (Sandbox Code Playgroud)