C++ 变量销毁
C++ Variable destruction
假设我有这个:
std::wstring str = std::to_wstring(100);
str = std::to_wstring(1000); // Is the previous str destroyed?
如果我将局部变量重新分配给另一个变量,旧的会被销毁吗?
以旧换新,只复制成员。考虑一个简单的赋值实现:
struct foo {
int value;
foo& operator=(const foo& other) {
value = other.value;
return *this;
}
};
赋值后 a = b;
对象 a
仍然是同一个对象。如果 foo
管理资源,operator=
当然必须考虑到这一点,您可以放心地假设所有标准容器都没有损坏。
Is the previous str
destroyed?
是。您分享的代码片段中没有发生内存管理,都是自动存储。
假设我有这个:
std::wstring str = std::to_wstring(100);
str = std::to_wstring(1000); // Is the previous str destroyed?
如果我将局部变量重新分配给另一个变量,旧的会被销毁吗?
以旧换新,只复制成员。考虑一个简单的赋值实现:
struct foo {
int value;
foo& operator=(const foo& other) {
value = other.value;
return *this;
}
};
赋值后 a = b;
对象 a
仍然是同一个对象。如果 foo
管理资源,operator=
当然必须考虑到这一点,您可以放心地假设所有标准容器都没有损坏。
Is the previous
str
destroyed?
是。您分享的代码片段中没有发生内存管理,都是自动存储。