'Is there some agreement about memory allocation?
class http_client {
public:
void init(const char url*);
void download();
}
int main() {
http_client c1;
{
char url[] = "www.example.com"; // url allocated on stack
c1.init(url);
} // <<<<< url is destroyed
c1.connect();
// do something else
}
In the above example there are two possibilites:
- http_client.init() alloactes memory for url, copies it and stores somewhere for future use
- http_client.init() stores only a pointer to url
In the variant №2 the c1.connect() will fail because url is destroyed before conenct();
In general both variants are possible. Sometimes it is desired to avoid extra copying of strings, arrays or other containers, especially when there is a bunch of abstraction layers, each storing a copy of a string.
The only way to distinguish from these two variants is to look into documentation or inside the init() method, to see does it store string content or just a pointer.
Is there some recommendation, or agreement, or naming convention of methods that make a deep copy of arguments and methods that copy only a pinter/reference ?
Solution 1:[1]
Is there some recommendation
Yes. Storing the data inside the class is recommended default choice. This is because it is safer and less reliant on documentation.
However, it's typically preferred to initialise using a constructor and not a normal member function.
or naming convention of methods
There are loose naming conventions for types. Types named like "view" or "ptr" or "ref" often refer to objects stored elsewhere. Since types that don't have reference semantics are the default choice, they don't need a naming hint.
Furthermore, constructors that accept pointers parameters are more often considered to potentially retain the reference for later use, while such consideration isn't typical when the parameter is a reference. That's not necessarily safe assumption when name is like "ref" etc though. Consider std::reference_wrapper
as such exception.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |