Skip to content

Commit

Permalink
Added some - a shared_ptr wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
lisitsyn authored and Björn Esser committed Feb 9, 2015
1 parent 85a709e commit 3bf51e8
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/shogun/base/some.h
@@ -0,0 +1,39 @@
#ifndef __SG_HELPERS_H__
#define __SG_HELPERS_H__

#include <memory>

#include <shogun/base/SGObject.h>

namespace shogun
{

/** Shogun synonym for the std::shared_ptr
*/
template <typename T>
class Some : public std::shared_ptr<T>
{
public:
Some(const std::shared_ptr<T>& shared)
: std::shared_ptr<T>(shared)
{

}
};

/** Creates an instance of any class
* that is wrapped with a shared pointer like
* structure @ref Some
*
*/
template <typename T, class... Args>
Some<T> some(Args&&... args)
{
T* ptr = new T(args...);
SG_REF(ptr);
return std::shared_ptr<T>(ptr, [](T* p) { SG_UNREF(p); });
}

};

#endif
25 changes: 25 additions & 0 deletions tests/unit/base/Some_unittest.cc
@@ -0,0 +1,25 @@
#include <shogun/base/some.h>
#include <shogun/kernel/GaussianKernel.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(Some,basic)
{
// raw pointer to the kernel
CKernel* raw = NULL;
// local scope to create kernel
{
auto kernel = some<CGaussianKernel>();
raw = kernel.get();
SG_REF(raw);
EXPECT_TRUE(kernel->equals(raw));

// reference is held
EXPECT_EQ(2, kernel->ref_count());
}
EXPECT_TRUE(raw);
// last references now
EXPECT_EQ(1, raw->ref_count());
SG_UNREF(raw);
}

0 comments on commit 3bf51e8

Please sign in to comment.