以下代码有效。但我不确定这样写是否真的可以。
class A {
private:
struct packet {
string header;
string data;
}
vector<packet > packets;
public:
void add_packet(string h, string d) {
struct packet p1; // Isnt this variable on stack and will be destroyed at the end of the function?
p1.header = h;
p1.data = d;
packets.push_back(p1); // Is it ok to add the variable on stack to a member variable?
}
void print_packets() {
// Iterates over the packets and prints header and data
}
}
Run Code Online (Sandbox Code Playgroud)
void push_back (const value_type& val);是 push_back 的原型。所以,我相信数据包向量只存储变量的引用(在堆栈上)。我的问题是add_packet(h, d) 返回后,存储在向量中的引用是否仍然有效?
你不能仅仅通过它的签名来判断一个函数会对一个参数做什么。即使你打电话
void push_back (const value_type& val);
Run Code Online (Sandbox Code Playgroud)
push_back实际上是要制作一个副本val并将该副本存储在向量中。这意味着没有悬空引用。
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |