C++ choose overloaded constructor for a stack object by condition - c++

I want something like this:
if (customLocation.isEmpty())
{
KUrl url;
}
else
{
KUrl url(customLocation);
}
/* use url */

Any reason you can't do
KUrl url;
if (!customLocation.isEmpty())
{
url = KUrl(customLocation);
}
/* use url */
or
KUrl url = customLocation.isEmpty() ? KUrl() : KUrl(customLocation);

The usual C++ constructs intentionally create a very tight coupling between allocation and initialization. Thus, ordinarily you would need to use dynamic allocation to be able to dynamically specify the constructor to use. And dynamic allocation is probably some orders of magnitude more inefficient than the slight overhead that you're trying to avoid…
However, with C++11 you can use aligned storage and placement new.
The catch is that the KUrl class will most likely use dynamic allocation internally, and then all that the optimization accomplishes is to waste programmer's time: both your time initially, and the time of anyone later maintaining the code.

Any reason why this won't work?
KUrl url;
if (!customLocation.isEmpty())
url = customLocation;

KUrl url;
if (!cusomLocation.isEmpty())
{
url = KUrl( customLocation );
}

Here you have no copy of KUrl being done
boost::optional<KUrl> ourl;
if(customLocation.isEmpty()) {
ourl = boost::in_place();
} else {
ourl = boost::in_place(customLocation);
}
KUrl &url = *ourl;
Fun aside, I would recommend Jacks solutions (if it works with your type) :)

Related

C++ few istream pointer and refferecnes and refactoring

The function below works, but it's seems to me it has very bad smell.
My project communicate with device over HTTP, it has some url with digest authentication, some pages without.
Some url compressed with deflate, some none.
So my function has 3 different way to get istream.
And i need to read istream in one place in the bottom of function.
But as said good people from another my question C++ variable visable scopes and strems, pointers in this case is bad.
And in this code in some cases creates dynamic object.
Poco::InflatingInputStream* inflater = new Poco::InflatingInputStream(*respStreamPtr);
And this is path to memory leaks?
If create inflater without new statement, then *respStreamPtr has no data out of if block scope.
So, please give me advice how to refactor this code in right way.
std::ostream& requestStream = session->sendRequest(request);
istream* respStreamPtr;
respStreamPtr = &session->receiveResponse(response);
if (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED)
{
credentials->authenticate(request, response);
session->sendRequest(request);
respStreamPtr = &session->receiveResponse(response);
}
if (response.has("Content-Encoding") && response.get("Content-Encoding") == "deflate") {
Poco::InflatingInputStream* inflater = new Poco::InflatingInputStream(*respStreamPtr);
respStreamPtr = &std::istream(inflater->rdbuf());
}
std::ostringstream stringStream;
stringStream << respStreamPtr->rdbuf();
responseBody = stringStream.str();
Yes, that will be a memory leak, as every time you use new it will create a new object, which you never delete
However, you use the inflater variable outside of the scope it's declared in, so currently have no way of nicely deleting it without modifying other code. For a simple fix, you could just declare Poco::InflatingInputStream* inflater = nullptr; at the top of your code, then delete it at the end.
I'd strongly recommend reading up on how to manage memory correctly in c++, and even taking a look at smart pointers (but not without learning the fundamentals first)
Poco actually has functionality which does a lot of what you're trying to do, so your example could be easily condensed (disclaimer: untested):
session->sendRequest(request);
auto& responseStream = session->receiveResponse(response);
if (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED)
{
credentials->authenticate(request, response);
session->sendRequest(request);
responseStream = session->receiveResponse(response);
}
if (response.has("Content-Encoding") && response.get("Content-Encoding") == "deflate")
{
Poco::InflatingInputStream inflater(responseStream);
StreamCopier::copyStream(inflater, responseStream);
}
responseBody << responseStream;

Proper memory control in gSoap

I'm currently developing application using gSoap library and has some misunderstanding of proper usage library. I has generated proxy object (-j flag) which wrapped my own classes, as you can see below. Application must work 24/7 and connect simultaneously to many cameras (~50 cameras), so after every request i need to clear all temporary data. Is it normal usage to call soap_destroy() and soap_end() after every request? Because it seem's overkill to do it after each request. May be exists another option of proper usage?
DeviceBindingProxy::destroy()
{
soap_destroy(this->soap);
soap_end(this->soap);
}
class OnvifDeviceService : public Domain::IDeviceService
{
public:
OnvifDeviceService()
: m_deviceProxy(new DeviceBindingProxy)
{
soap_register_plugin(m_deviceProxy->soap, soap_wsse);
}
int OnvifDeviceService::getDeviceInformation(const Access::Domain::Endpoint &endpoint, Domain::DeviceInformation *information)
{
_tds__GetDeviceInformation tds__GetDeviceInformation;
_tds__GetDeviceInformationResponse tds__GetDeviceInformationResponse;
setupUserPasswordToProxy(endpoint);
m_deviceProxy->soap_endpoint = endpoint.endpoint().c_str();
int result = m_deviceProxy->GetDeviceInformation(&tds__GetDeviceInformation, tds__GetDeviceInformationResponse);
m_deviceProxy->soap_endpoint = NULL;
if (result != SOAP_OK) {
Common::Infrastructure::printSoapError("Fail to get device information.", m_deviceProxy->soap);
m_deviceProxy->destroy();
return -1;
}
*information = Domain::DeviceInformation(tds__GetDeviceInformationResponse.Manufacturer,
tds__GetDeviceInformationResponse.Model,
tds__GetDeviceInformationResponse.FirmwareVersion);
m_deviceProxy->destroy();
return 0;
}
}
To ensure proper allocation and deallocation of managed data:
soap_destroy(soap);
soap_end(soap);
You want to do this often to avoid memory to fill up with old data. These calls remove all deserialized data and data you allocated with the soap_new_X() and soap_malloc() functions.
All managed allocations are deleted with soap_destroy() followed by soap_end(). After that, you can start allocating again and delete again, etc.
To allocate managed data:
SomeClass *obj = soap_new_SomeClass(soap);
You can use soap_malloc for raw managed allocation, or to allocate an array of pointers, or a C string:
const char *s = soap_malloc(soap, 100);
Remember that malloc is not safe in C++. Better is to allocate std::string with:
std::string *s = soap_new_std__string(soap);
Arrays can be allocated with the second parameter, e.g. an array of 10 strings:
std::string *s = soap_new_std__string(soap, 10);
If you want to preserve data that otherwise gets deleted with these calls, use:
soap_unlink(soap, obj);
Now obj can be removed later with delete obj. But be aware that all pointer members in obj that point to managed data have become invalid after soap_destroy() and soap_end(). So you may have to invoke soap_unlink() on these members or risk dangling pointers.
A new cool feature of gSOAP is to generate deep copy and delete function for any data structures automatically, which saves a HUGE amount of coding time:
SomeClass *otherobj = soap_dup_SomeClass(NULL, obj);
This duplicates obj to unmanaged heap space. This is a deep copy that checks for cycles in the object graph and removes such cycles to avoid deletion issues. You can also duplicate the whole (cyclic) managed object to another context by using soap instead of NULL for the first argument of soap_dup_SomeClass.
To deep delete:
soap_del_SomeClass(obj);
This deletes obj but also the data pointed to by its members, and so on.
To use the soap_dup_X and soap_del_X functions use soapcpp2 with options -Ec and -Ed, respectively.
In principle, static and stack-allocated data can be serialized just as well. But consider using the managed heap instead.
See https://www.genivia.com/doc/databinding/html/index.html#memory2 for more details and examples.
Hope this helps.
The way memory has to be handled is described in Section 9.3 of the GSoap documentation.

SqlConnection's executeAndWait causes memory leak on BB10

When I call executeAndWait and just when the reply is returned I see a 76KB of memory increase in heap. I don't know why it happens. How do I clean this memory? My connection creation with db is following,
bool DBHelper::checkConnection(bool isAsynch)
{
if(sqlConnector && dbFile->exists())
{
return true;
}
if (dbFile->exists())
{
sqlConnector = new SqlConnection(dbPath, "connect");
connect(sqlConnector, SIGNAL(reply(const bb::data&colon;:DataAccessReply&)), this,
SLOT(onLoadAsyncResultData(const bb::data&colon;:DataAccessReply&)));
return true;
}
return false;
}
The call to the executeAndWait is in this function,
void DBHelper::execute (const QVariant &criteria,int id,bool isAsynch)
{
if (checkConnection(isAsynch))
{
if(!isAsynch)
{
DataAccessReply reply= sqlConnector->executeAndWait(criteria, id); // memory leak happens when the reply is found.
this->onLoadSynchResultData(reply);
}
}
}
Documentation link is in here.
Thanks.
Are you sure it is a memory leak and not some inner mechanism of DataAccessReply class? Have you tried to ckeck it with valgrind or some similar tool?
From your allocation by using new and subsequent assignment I presume the type of sqlConnector is a pointer to something. Although it might not be the solution you are looking for I recommend using some smart pointer type as these are always more leak-proof.
If interested see e. g. boost::shared_ptr or C++11 std::shared_ptr according to what is available to you.
Also (call me pedantic here) I would not use if(sqlConnector) even if it might be doing what you are expecting by implicit casting. I would explicitly use if(sqlConnector != NULL) (or something similar) and double check sqlConnector gets (also explicitly) initialized properly.

Serial allocators/deallocators

I have a code that has a large number of mallocs and device-specific API mallocs (I'm programming on a GPU, so cudaMalloc).
Basically my end of my beginning of my code is a big smorgasbord of allocation calls, while my closing section is deallocation calls.
As I've encapsulated my global data in structures, the deallocations are quite long, but at least I can break them into a separate function. On the other hand, I would like a shorter solution. Additionally an automatic deallocator would reduce the risk of memory leaks created if I forget to explicitly write the deallocation in the global allocator function.
I was wondering whether it'd be possible to write some sort of templated class wrapper that can allow me to "register" variables during the malloc/cudaMalloc process, and then at the end of simulation do a mass loop-based deallocation (deregistration). To be clear I don't want to type out individual deallocations (free/cudaFrees), because again this is long and undesirable, and the assumption would be that anything I register won't be deallocated until the device simulation is complete and main is terminating.
A benefit here is that if I register a new simulation duration variable, it will automatically deallocate, so there's no danger of me forgetting do deallocate it and creating a memory leak.
Is such a wrapper possible?
Would you suggest doing it?
If so, how?
Thanks in advance!
An idea:
Create both functions, one that allocates memory and provides valid pointers after register them in a "list" of allocated pointers. In the second method, loop this list and deallocate all pointers:
// ask for new allocated pointer that will be registered automatically in list of pointers.
pointer1 = allocatePointer(size, listOfPointers);
pointer2 = allocatePointer(size, listOfPointers);
...
// deallocate all pointers
deallocatePointers(listOfPointers);
Even, you may use different listOfPointers depending of your simulation scope:
listOfPointer1 = getNewListOfPointers();
listOfPointer2 = getNewListOfPointers();
....
p1 = allocatePointer(size, listOfPointer1);
p2 = allocatePointer(size, listOfPointer2);
...
deallocatePointers(listOfPointers1);
...
deallocatePointers(listOfPointers2);
There are many ways to skin a cat, as they say.
I would recommend thrust's device_vector as a memory management tool. It abstracts allocation, deallocation, and memcpy in CUDA. It also gives you access to all the algorithms that Thrust provides.
I wouldn't recommend keeping random lists of unrelated pointers as Tio Pepe recommends. Instead you should encapsulate related data into a class. Even if you use thrust::device_vector you may want to encapsulate multiple related vectors and operations on them into a class.
The best choice is probably to use the smart pointers from C++ boost library, if that is an option.
If not, the best you can hope for in C is a program design that allows you to write allocation and deallocation in one place. Perhaps something like the following pseudo code:
while(!terminate_program)
{
switch(state_machine)
{
case STATE_PREOPERATIONAL:
myclass_init(); // only necessary for non-global/static objects
myclass_mem_manager();
state_machine = STATE_RUNNING;
break;
case STATE_RUNNING:
myclass_do_stuff();
...
break;
...
case STATE_EXIT:
myclass_mem_manager();
terminate_program = true;
break;
}
void myclass_init()
{
ptr_x = NULL;
ptr_y = NULL;
/* Where ptr_x, ptr_y are some of the many objects to allocate/deallocate.
If ptr is a global/static, (static storage duration) it is
already set to NULL automatically and this function isn't
necessary */
}
void myclass_mem_manager()
{
ptr_x = mem_manage (ptr_x, items_x*sizeof(Type_x));
ptr_y = mem_manage (ptr_y, items_y*sizeof(Type_y));
}
static void* mem_manage (const void* ptr, size_t bytes_n)
{
if(ptr == NULL)
{
ptr = malloc(bytes_n);
if (ptr == NULL)
{} // error handling
}
else
{
free(ptr);
ptr = NULL;
}
return ptr;
}

Lazy object creation in C++, or how to do zero-cost validation

I've stumbled across this great post about validating parameters in C#, and now I wonder how to implement something similar in C++. The main thing I like about this stuff is that is does not cost anything until the first validation fails, as the Begin() function returns null, and the other functions check for this.
Obviously, I can achieve something similar in C++ using Validate* v = 0; IsNotNull(v, ...).IsInRange(v, ...) and have each of them pass on the v pointer, plus return a proxy object for which I duplicate all functions.
Now I wonder whether there is a similar way to achieve this without temporary objects, until the first validation fails. Though I'd guess that allocating something like a std::vector on the stack should be for free (is this actually true? I'd suspect an empty vector does no allocations on the heap, right?)
Other than the fact that C++ does not have extension methods (which prevents being able to add in new validations as easily) it should be too hard.
class Validation
{
vector<string> *errors;
void AddError(const string &error)
{
if (errors == NULL) errors = new vector<string>();
errors->push_back(error);
}
public:
Validation() : errors(NULL) {}
~Validation() { delete errors; }
const Validation &operator=(const Validation &rhs)
{
if (errors == NULL && rhs.errors == NULL) return *this;
if (rhs.errors == NULL)
{
delete errors;
errors = NULL;
return *this;
}
vector<string> *temp = new vector<string>(*rhs.errors);
std::swap(temp, errors);
}
void Check()
{
if (errors)
throw exception();
}
template <typename T>
Validation &IsNotNull(T *value)
{
if (value == NULL) AddError("Cannot be null!");
return *this;
}
template <typename T, typename S>
Validation &IsLessThan(T valueToCheck, S maxValue)
{
if (valueToCheck < maxValue) AddError("Value is too big!");
return *this;
}
// etc..
};
class Validate
{
public:
static Validation Begin() { return Validation(); }
};
Use..
Validate::Begin().IsNotNull(somePointer).IsLessThan(4, 30).Check();
Can't say much to the rest of the question, but I did want to point out this:
Though I'd guess that allocating
something like a std::vector on the
stack should be for free (is this
actually true? I'd suspect an empty
vector does no allocations on the
heap, right?)
No. You still have to allocate any other variables in the vector (such as storage for length) and I believe that it's up to the implementation if they pre-allocate any room for vector elements upon construction. Either way, you are allocating SOMETHING, and while it may not be much allocation is never "free", regardless of taking place on the stack or heap.
That being said, I would imagine that the time taken to do such things will be so minimal that it will only really matter if you are doing it many many times over in quick succession.
I recommend to get a look into Boost.Exception, which provides basically the same functionality (adding arbitrary detailed exception-information to a single exception-object).
Of course you'll need to write some utility methods so you can get the interface you want. But beware: Dereferencing a null-pointer in C++ results in undefined behavior, and null-references must not even exist. So you cannot return a null-pointer in a way as your linked example uses null-references in C# extension methods.
For the zero-cost thing: A simple stack-allocation is quite cheap, and a boost::exception object does not do any heap-allocation itself, but only if you attach any error_info<> objects to it. So it is not exactly zero cost, but nearly as cheap as it can get (one vtable-ptr for the exception-object, plus sizeof(intrusive_ptr<>)).
Therefore this should be the last part where one tries to optimize further...
Re the linked article: Apparently, the overhaead of creating objects in C# is so great that function calls are free in comparison.
I'd personally propose a syntax like
Validate().ISNOTNULL(src).ISNOTNULL(dst);
Validate() contructs a temporary object which is basically just a std::list of problems. Empty lists are quite cheap (no nodes, size=0). ~Validate will throw if the list is not empty. If profiling shows even this is too expensive, then you just change the std::list to a hand-rolled list. Remember, a pointer is an object too. You're not saving an object just by sticking to the unfortunate syntax of a raw pointer. Conversely, the overhead of wrapping a raw pointer with a nice syntax is purely a compile-time price.
PS. ISNOTNULL(x) would be a #define for IsNotNull(x,#x) - similar to how assert() prints out the failed condition, without having to repeat it.