I follow some simple rules:
- don’t do manual memory allocations. If you find yourself writing a manual
delete
, stop and think twice. - use
std::string
instead of C-style strings - use
std::vector<T>
instead of C-arrays (orstd::array<T>
for fixed-sized arrays) - use
std::unique_ptr
andstd::make_unique
by default - use
std::shared_ptr
if necessary - use RAII wrappers for other resources, e.g. files
Your code can be written as simple as
// With C++17, we could use std::string_view for the input parameters
// I strongly prefer pure functions that don't mutate their arguments
std::string append(std::string const& s1, std::string const& s2) {
return s1 + s2;
}
// the same function mutating the input argument.
void append_mutate(std::string& s1, std::string const& s2) {
s1 += s2;
}
int main(){
std::string s = "string";
cout << s << endl;
s = append(s, " hello");
cout << s << endl;
append2(s, " welcome");
cout << s << endl;
}
I would also strongly advice against using C-style strings and especially C strings.If you are coming from a C background or don’t have much experience with C++, I would recommend A Tour of C++.
The idea of these classes is an example of RAII. The basic principle is to encapsulate resources, e.g. memory or files, into wrapper classes that own the resource and take care of acquisition and release in the constructor/destructor. This provides exception-safe, deterministic resource handling.