I have a class (simplified):
class a {
private:
std::vector<a> arguments;
public:
std::vector<a> getargs() { return arguments; }
};
Suppose, the class has a member function:
void a::bubble() {
arguments = arguments[0].getargs();
}
Is this kosher (in that the source of the data, arguments[0], is deleted as a result of the command)?
开发者_JS百科It works on my compiler, but I just wanted to check if the c++ standard guarantees the safety of this operation.
Yes, it is ok. The getargs() function is done before the assignment. It creates a temporary that exists for the lifetime of the complete instruction statement (everything to ;). That temporary is used in the call to the assignment operator for std::vector (works for raw types too though). Everything is kosher and will work just fine.
Why wouldn't it be legal? Of course you will still go to the programmer's hell for this, but then again it's not really you, it's C++.
I've no idea what do you want to do, but it should work fine. The only problem is that you must to be sure that you have at least 1 element in arguments.
精彩评论