方法一:std::unique_ptr<char[]> getHello(){ char* str = new char[12]; strcpy( str, "HelloWorld\n" ); return std::unique_ptr<char[]>(str);}std::unique_ptr<char[]> testStr = getHello();============================================方法二:static void stringDeleter( char* str ){ delete[] str;};std::shared_ptr<char> getHelloShared(){ char* str = new char[12]; strcpy( str, "HelloWorld\n" ); return std::shared_ptr<char>( str, stringDeleter );}std::shared_ptr<char> testStr2 = getHelloShared();============================================方法三:std::vector<char> getHelloVector(){ std::vector<char> helloVector( 12 ); strcpy( helloVector.data(), "HelloWorld\n" ); return helloVector;}std::vector<char> testStr3 = getHelloVector();============================================利用RAII可以確保記憶體會被正確釋放不過假如要對付字串,最簡潔漂亮又有效率的寫法還是std::string...std::string getHelloString(){ return "HelloWorld\n";}std::string testStr4 = getHelloString();compiler極有可能使上面這一行省略建構暫時物件,只呼叫一次testStr4的普通建構子再不然靠著move建構子不會真的完整複製物件再再不然std::string也還有copy on write...