简体   繁体   English

C++:使用向量和迭代器时出现错误:std::bad_alloc

[英]C++: get error: std::bad_alloc when using vector and iterator

I am using mailio library and I get into trouble when I want to get all elements in a vector.我正在使用mailio 库,当我想获取向量中的所有元素时遇到了麻烦。

string msg = "Subject: " + mail -> subject() + "\nFrom: ";
for(auto address = ( mail -> from() ).addresses.begin(); address != ( mail -> from() ).addresses.end(); ++address ){ //address is not empty
    msg.append( address -> name );//     <----here
}

Here are the brief definations of class message :以下是 class message的简要定义:

class MAILIO_EXPORT message : public mime
{
...
public:
    mailboxes from() const;
...
}

struct MAILIO_EXPORT mailboxes
{
    ...
    std::vector<mail_address> addresses;
    ...
}

struct MAILIO_EXPORT mail_address
{
    ...
    std::string name;
    ...
}


The program terminates and returns get error: std::bad_alloc .程序终止并返回get error: std::bad_alloc I don't know what's wrong, though I still managed to solved it with following code:我不知道出了什么问题,尽管我仍然设法用以下代码解决了它:

string msg = "Subject: " + mail -> subject() + "\nFrom: ";
auto add = ( mail -> from() ).addresses; 
for(auto address = add.begin(); address != add.end(); ++address ){
     msg.append( address -> name );
}

Maybe I tried to modify one or some of these const values unconsciously.也许我试图无意识地修改其中一个或一些 const 值。 But I am not.但我不是。

If the from() doesn't return a reference then it makes a copy of the struct, including copying the std::vector .如果from()没有返回引用,那么它会复制结构,包括复制std::vector This means in your loop you get two different vectors of which you take begin() and end() respectively.这意味着在您的循环中,您将获得两个不同的向量,分别采用begin()end() You're not allowed to loop between these since the begin iterator will most likely never match the end, especially before going out of bounds.不允许在这些之间循环,因为开始迭代器很可能永远不会匹配结束,尤其是在超出范围之前。

In the second code there's one copy and you use iterators from it so they will work.在第二个代码中有一个副本,您可以从中使用迭代器,以便它们可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM