C/C++
last updated 2014-03
how to clean up after a child thread
even when the child thread shuts down gracefully - i.e. the thread's function returns, or the thread calls pthread_exit() - there might still be a memory leak due to the thread data allocated during the call to pthread_create()
there are 3 options to handle this:
- stop the thread from the creator thread using
pthread_cancel() - wait for the thread to shut down gracefully, and then
pthread_join()with the thread (yes, "join with the stopped thread") - this call returns immediately, and frees up the thread's resources - have the thread clean up on its own, by
pthread_detach()-ing the thread
non-blocking IO using sockets
to get a non-blocking IO, you can
- set the socket to non-blocking:
// for fcntl()
#include <unistd.h>
#include <fcntl.h>
// for ioctl()
#include <sys/ioctl.h>
int set_nonblocking(int fd)
{
int flags;
#if defined(O_NONBLOCK)
if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
#else
flags = 1;
return ioctl(fd, FIOBIO, &flags);
#endif
}
- or, you can use
MSG_DONTWAITasflagsin the calls torecv(),recvfrom(),send(), andsendto()
or both… can't hurt ;-)
shared libraries on Linux+GCC
shared libraries on Linux typically have a linker name, a soname, and a real name
the linker name is typically libtest.so. the soname is the linker name with a version, typically libtest.so.1, and the real name is the name of the file, typically libtest.so.1.0.3
in reality, libtest.so.1.0.3 would be the actual file, with two links:
libtest.so.1 -> libtest.so.1.0.3
libtest.so -> libtest.so.1
example
here's an example of a test_so library - .h and .c files, how to build and link the .so file, and using this library from Python using ctypes
test_so.h
#ifndef __TEST_SO__
#define __TEST_SO__
int test_so_string(const char* str);
int test_so_int(int i);
#endif//__TEST_SO__
test_so.c
#include "test_so.h"
#include <string.h>
int test_so_string(const char* str)
{
return strlen(str);
}
int test_so_int(int i)
{
return -i;
}
compiling and linking
gcc -fPIC -O3 -c -Wall test_so.c
gcc -shared -Wl,-soname,libtest_so.so.1 -o libtest_so.so.1.0.0 test_so.o -lc
now you can also create the "upper links":
ln -s libtest_so.so.1.0.0 libtest_so.so.1
ln -s libtest_so.so.1 libtest_so.so
using from Python - test_so.py
import ctypes
lib = ctypes.CDLL("./libtest_so.so")
print "int -> int fcall works" if lib.test_so_int(1) == -1 else "int -> int fcall DOESN'T WORK!"
print "string -> int fcall works" if lib.test_so_string("hello there!") == 12 else "string -> int fcall DOESN'T WORK!"
will output:
$ python test_so.py
int -> int fcall works
string -> int fcall works
see the ctypes library for more info
notes
if your library needs some other shared library, link it in when building the .so (gcc -shared … -lother), so the dependency is recorded in your library and gets loaded with it
the -Wl,-export-dynamic (-rdynamic) option is for the program - it exports all of the program's symbols, so that libraries loaded with dlopen() can call back into it
singleton
traditional approach
// Singleton.h
class Singleton
{
private:
Singleton() { }
Singleton(const Singleton&) { }
Singleton& operator=(const Singleton&) { return *this; }
~Singleton() { }
static Singleton* inst;
public:
static Singleton* instance();
};
// Singleton.cpp
#include "Singleton.h"
Singleton* Singleton::inst = NULL;
Singleton* Singleton::instance()
{
return inst ? inst : inst = new Singleton;
}
stack-based singleton
i usually prefer this version over the dynamically allocated one, as the destructor will be called (at some point in time), which lets you free up all resources obtained during the lifetime - esp. close files, sockets, etc.
class Singleton
{
private:
Singleton();
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
~Singleton();
// ...
public:
static Singleton& instance()
{
static Singleton inst; // constructed on the first call
return inst;
}
// ...
};
std::move semantics
mostly based on stackoverflow.com - What is move semantics?
consider a simple string class that manages its string buffer. it thus follows the Rule of Three (if the class has any of the following, then it should probably have all of them - destructor, copy constructor, and copy assignment operator; in C++11 this has been extended to the Rule of Five, adding move constructor and move assignment operator - see further on)
#include <cstring>
#include <algorithm>
class string
{
char* data;
size_t size;
public:
string(const char* p)
{
data = new char[size = strlen(p) + 1];
memcpy(data, p, size);
}
~string()
{
if (data)
delete[] data;
}
string(const string& that)
{
data = new char[size = that.size];
memcpy(data, that.data, size);
}
};
this allows you to use the class in the following expressions:
string a(x); // (1)
string b(x + y); // (2)
string c(some_function_returning_a_string()); // (3)
note that only in case (1) the deep copy is actually necessary - cases (2) and (3) currently make a deep copy of a temporary object (that itself was some deep copy of other objects). in case (1), the string object is an lvalue, while in cases (2) and (3) it's an rvalue
C++11 introduces the "rvalue reference", which allows us to detect an rvalue via function overloading. we can then do pretty much anything with the object, as long as we leave it in some valid state (even though it's an rvalue/temp object, its destructor will still be called). the move constructor would then be:
string::string(string&& that)
{
data = that.data;
size = that.size;
that.data = 0;
that.size = 0;
}
here we pretty much stole the data, and since we're working with a temp object that gets destroyed in a moment, there's no problem doing so
the move assignment operator is defined as
string& string::operator=(string that)
{
std::swap(data, that.data);
std::swap(size, that.size);
return *this;
}
note that we don't have the rvalue reference here - the compiler chooses the move constructor to create the that object if the original object is an rvalue
when writing a = b, where an lvalue is on the right hand side, the copy constructor is used to construct the that parameter (object), so swapping with it does exactly what we need. while with a = x + y, the compiler chooses the move constructor to initialize that, and then swapping is equivalent to moving the data
converting between std::string and std::wstring in C++11
// one-liners
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes("some string");
std::string str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(L"some string");
// small functions
std::wstring s2ws(const std::string& str)
{
typedef std::codecvt_utf8<wchar_t> convert_type;
std::wstring_convert<convert_type, wchar_t> converter;
return converter.from_bytes(str);
}
std::string ws2s(const std::wstring& str)
{
typedef std::codecvt_utf8<wchar_t> convert_type;
std::wstring_convert<convert_type, wchar_t> converter;
return converter.to_bytes(str);
}
update 2026 - std::wstring_convert and std::codecvt_utf8 are deprecated since C++17, and there's no drop-in replacement in the standard library - they still compile (with warnings), otherwise it's ICU or the platform's own calls