我希望一个类Watchdog
在POSIX共享内存中创建其对象。
请记住此类的源代码已编译到静态库中,而方法的源代码实际上已放置在c ++源文件中。
我对此的第一次尝试是在类中使用static Watchdog* createWatchdog(param p1, param p2, ...)
函数,并将其用作包装程序以分配对象的内存,然后调用放置位置new (ptr) Watchdog
。
这很好,但是我想起了new
运算符可能会重载,所以我想出了这个解决方案:
Watchdog.h
#pragma once
#include <string>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
namespace og {
class Watchdog {
public:
Watchdog();
Watchdog(const std::string t_name, void* t_data, const size_t t_datSize);
static void* operator new(size_t count, const std::string t_name, const size_t t_datSize);
protected:
Watchdog(const Watchdog&) = delete;
Watchdog& operator=(const Watchdog&) = delete;
private:
std::string m_name;
void* m_data;
size_t m_datSize;
// and other member variables
}; // end class Watchdog
} // end namespace
Watchdog.cxx
#include "Watchdog.h"
using namespace og;
Watchdog::Watchdog()
{}
Watchdog::Watchdog(const std::string t, void* t_data, const size_t size)
{}
void* operator new(size_t count, const std::string t_name, const size_t dat)
{
int fd;
void* obj;
// removed all error checks for the sake of the example
fd = shm_open(t_name.c_str(), O_CREAT | O_EXCL | O_RDWR, 0600);
(void) ftruncate(fd, sizeof(Watchdog));
obj = mmap(0x0, sizeof(Watchdog), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
(void) shm_unlink(t_name.c_str());
return obj;
}
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED( VERSION 2.6 )
PROJECT( WATCHDOG C CXX )
SET( CMAKE_CXX_STANDARD 11)
SET( CMAKE_CXX_STANDARD_REQUIRED OFF)
SET( watchdog_HEADERS
Watchdog.h
)
SET( watchdog_SRC
Watchdog.cxx
${watchdog_HEADERS}
)
SET( CMAKE_CXX_FLAGS_DEBUG "-g3 -Wall -Wextra -Wpedantic")
ADD_LIBRARY( watchdog STATIC ${watchdog_SRC} )
TARGET_LINK_LIBRARIES( watchdog -lrt )
用cmake . && make
编译
main.cxx
#include "Watchdog.h"
using namespace og;
int
main()
{
Watchdog* W;
W = new ("test", 20) Watchdog;
}
g++ main.cxx -L. -lwatchdog -lrt
编译会引发链接错误:/usr/lib64/gcc/x86_64-suse-linux/9/../../../../x86_64-suse-linux/bin/ld: /tmp/ccDncNvb.o: in function `main':
main.cxx:(.text+0x3c): undefined reference to `og::Watchdog::operator new(unsigned long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned long)'
collect2: error: ld returned 1 exit status
return ::operator new (sz)
或return ::operator new(sz, ptr)
,但是我看不到如何调用非默认构造函数(例如类规范中的第二个)。我希望一个类Watchdog在POSIX共享内存中创建其对象。请记住,此类的源代码已编译到静态库中,并且方法的源代码实际上已放置在...
问题1: