使用已从中移动的对象
Usage of objects that have been moved from
以下代码可以在我的计算机上运行,但这是否保证符合 C++ 标准?
void do_stuff(std::string);
std::string s;
while(std::cin >> s){
do_stuff(std::move(s));
}
根据我对标准的理解,从 移动的对象处于有效但未指定的状态,并且只值得销毁。因此,代码不能保证有效。
作为扩展,考虑到 Notification
class 的知识以及 get_notification
覆盖成员 details
的事实,以下是否有效?
struct Notification{
string details;
};
string get_string();
void do_more_stuff(Notification);
void get_notification(Notification& n){
n.details = get_string();
}
Notification n;
while(get_notification(n)){
do_more_stuff(std::move(n));
}
From my understanding of the standard, objects that are moved from are left in a valid but unspecified state,
这部分是真实的。
and are only worthy of destruction
这部分是不正确的。 您可以对从中移出的对象执行的操作:任何没有先决条件的操作。例如,clear()
对字符串没有前提条件,因此您可以 clear()
一个 moved-from 字符串。那时,您处于特定状态。同样,erase()
没有前提条件。
operator>>
是另一个没有前置条件的操作(确实是指定调用erase()
)。所以这段代码:
while(std::cin >> s){
do_stuff(std::move(s));
}
其实还好。
以下代码可以在我的计算机上运行,但这是否保证符合 C++ 标准?
void do_stuff(std::string);
std::string s;
while(std::cin >> s){
do_stuff(std::move(s));
}
根据我对标准的理解,从 移动的对象处于有效但未指定的状态,并且只值得销毁。因此,代码不能保证有效。
作为扩展,考虑到 Notification
class 的知识以及 get_notification
覆盖成员 details
的事实,以下是否有效?
struct Notification{
string details;
};
string get_string();
void do_more_stuff(Notification);
void get_notification(Notification& n){
n.details = get_string();
}
Notification n;
while(get_notification(n)){
do_more_stuff(std::move(n));
}
From my understanding of the standard, objects that are moved from are left in a valid but unspecified state,
这部分是真实的。
and are only worthy of destruction
这部分是不正确的。 您可以对从中移出的对象执行的操作:任何没有先决条件的操作。例如,clear()
对字符串没有前提条件,因此您可以 clear()
一个 moved-from 字符串。那时,您处于特定状态。同样,erase()
没有前提条件。
operator>>
是另一个没有前置条件的操作(确实是指定调用erase()
)。所以这段代码:
while(std::cin >> s){
do_stuff(std::move(s));
}
其实还好。