temporary

Disallowing creation of the temporary objects

☆樱花仙子☆ 提交于 2019-11-26 07:46:26
问题 While debugging crash in a multithreaded application I finally located the problem in this statement: CSingleLock(&m_criticalSection, TRUE); Notice that it is creating an unnamed object of CSingleLock class and hence the critical section object gets unlocked immediately after this statement. This is obviously not what the coder wanted. This error was caused by a simple typing mistake. My question is, is there someway I can prevent the temporary object of a class being created at the compile

Why is it legal to borrow a temporary?

你离开我真会死。 提交于 2019-11-26 02:25:56
问题 Coming from C++, I\'m rather surprised that this code is valid in Rust: let x = &mut String::new(); x.push_str(\"Hello!\"); In C++, you can\'t take the address of a temporary, and a temporary won\'t outlive the expression it appears in. How long does the temporary live in Rust? And since x is only a borrow, who is the owner of the string? 回答1: Why is it legal to borrow a temporary? It's legal for the same reason it's illegal in C++ — because someone said that's how it should be. How long does

Lifetime of temporaries

喜欢而已 提交于 2019-11-26 00:25:51
问题 The following code works fine, but why is this correct code? Why is the \"c_str()\" pointer of the temporary returned by foo() valid? I thought, that this temporary is already destroyed when bar() is entered - but it doesn\'t seem to be like this. So, now I assume that the temporary returned by foo() will be destroyed after the call to bar() - is this correct? And why? std::string foo() { std::string out = something...; return out; } void bar( const char* ccp ) { // do something with the

Does a const reference class member prolong the life of a temporary?

风格不统一 提交于 2019-11-25 21:47:45
问题 Why does this: #include <string> #include <iostream> using namespace std; class Sandbox { public: Sandbox(const string& n) : member(n) {} const string& member; }; int main() { Sandbox sandbox(string(\"four\")); cout << \"The answer is: \" << sandbox.member << endl; return 0; } Give output of: The answer is: Instead of: The answer is: four 回答1: Only local const references prolong the lifespan. The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of