为什么下面的代码段打印:
Constructing Working on this
Constructing working on that
Destructing working on that
Destructing working on that
我希望";构造这个+那个";以及";破坏了这个";。
所以这里的想法是必须有一个对workingItem
的引用,然后在析构函数中做一些事情,如果有东西超出了范围。这似乎不起作用,我的问题是为什么?这会导致内存泄漏吗?还有为什么我不得到";破坏这个";因为我没有覆盖a
?
我可以通过将workingItem
设为指针来实现这一点,但我的问题是:是否也有一种方法可以通过使用ref来实现此操作?
#include <iostream>
class A {
private:
std::string str;
public:
A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; };
~A() { std::cout << "Destructing "<<str<<std::endl; };
};
int main() {
A a("Working on this");
A& workingItem=a;
A a2("working on that");
workingItem=a2;
}
实现operator=
以获得完整的图像:
#include <iostream>
class A {
private:
std::string str;
public:
A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; };
~A() { std::cout << "Destructing "<<str<<std::endl; };
A& operator=(const A& other){
std::cout << "assign " << other.str << " to " << str <<"n";
str = other.str;
return *this;
}
};
int main() {
A a("Working on this");
A& workingItem=a;
A a2("working on that");
workingItem=a2;
}
输出为:
Constructing Working on this
Constructing working on that
assign working on that to Working on this
Destructing working on that
Destructing working on that
不能重新绑定引用。该线A& workingItem=a;
将参考workingItem
初始化为参考a
。
这一行完全不同:workingItem=a2;
将a2
分配给workingItem
引用的对象,即a1
。与a1 = a2;
相同。因此,当main
返回时,您最终会得到两个相同的A
。
通常,重要的是要注意初始化T x = y;
和分配x = y;
之间的区别。