C ++如何在不删除对象的情况下将对象存储在数组中
C++ How to store object in arrays without them deleted
我想就我在学习C++时遇到的这个问题寻求帮助。我试图将对象直接存储到数组中,但意识到对象会立即被解构。我想不通为什么会这样。
#include <iostream>
class Thing{
public:
~Thing(){
std::cout<<"Thing destructing";
}
};
int main(){
Thing arr[1];
arr[0] = Thing();
int x;
std::cin>>x;
};
在此声明中
arr[0] = Thing();
使用默认的复制赋值运算符将此表达式创建的临时对象Thing()
分配给数组的元素。分配后临时对象被销毁。
为了更清楚运行这个演示程序。
#include <iostream>
class Thing
{
public:
~Thing()
{
std::cout<<"Thing " << i << " destructing\n";
}
Thing & operator =( const Thing & )
{
std::cout << "Thing " << i << " assigning\n";
return *this;
}
Thing() : i( ++n )
{
std::cout << "Thing " << i << " constructing\n";
}
private:
size_t i;
static size_t n;
};
size_t Thing::n = 0;
int main()
{
{
Thing arr[1];
arr[0] = Thing();
}
std::cin.get();
return 0;
}
它的输出是
Thing 1 constructing
Thing 2 constructing
Thing 1 assigning
Thing 2 destructing
Thing 1 destructing
假设您还不知道。
智能指针
#include <memory>
// ...
int main() {
std::shared_ptr<Thing> arr[1];
arr[0] = std::shared_ptr<Thing>(new Thing());
// ...
// <-- Is automatically deleted around here.
}
指针
不推荐;
使用指针看起来像:
int main() {
Thing *arr[1] = {};
arr[0] = new Thing();
int x;
std::cin >> x;
// WARNING: remember to manually delete.
delete arr[0];
} // <-- BTW, you don't need semi-colon.
我想就我在学习C++时遇到的这个问题寻求帮助。我试图将对象直接存储到数组中,但意识到对象会立即被解构。我想不通为什么会这样。
#include <iostream>
class Thing{
public:
~Thing(){
std::cout<<"Thing destructing";
}
};
int main(){
Thing arr[1];
arr[0] = Thing();
int x;
std::cin>>x;
};
在此声明中
arr[0] = Thing();
使用默认的复制赋值运算符将此表达式创建的临时对象Thing()
分配给数组的元素。分配后临时对象被销毁。
为了更清楚运行这个演示程序。
#include <iostream>
class Thing
{
public:
~Thing()
{
std::cout<<"Thing " << i << " destructing\n";
}
Thing & operator =( const Thing & )
{
std::cout << "Thing " << i << " assigning\n";
return *this;
}
Thing() : i( ++n )
{
std::cout << "Thing " << i << " constructing\n";
}
private:
size_t i;
static size_t n;
};
size_t Thing::n = 0;
int main()
{
{
Thing arr[1];
arr[0] = Thing();
}
std::cin.get();
return 0;
}
它的输出是
Thing 1 constructing
Thing 2 constructing
Thing 1 assigning
Thing 2 destructing
Thing 1 destructing
假设您还不知道。
智能指针
#include <memory>
// ...
int main() {
std::shared_ptr<Thing> arr[1];
arr[0] = std::shared_ptr<Thing>(new Thing());
// ...
// <-- Is automatically deleted around here.
}
指针
不推荐; 使用指针看起来像:
int main() {
Thing *arr[1] = {};
arr[0] = new Thing();
int x;
std::cin >> x;
// WARNING: remember to manually delete.
delete arr[0];
} // <-- BTW, you don't need semi-colon.